1、处理类
package com; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import javax.servlet.jsp.JspException; import javax.servlet.jsp.tagext.TagSupport; @SuppressWarnings("serial") public class TestTag extends TagSupport { private String longtime; public String getLongtime() { return longtime; } public void setLongtime(String longtime) { this.longtime = longtime; } @Override public int doStartTag() throws JspException { long l = 0l; if (null != longtime && "".equals(longtime)) { l = Long.parseLong(longtime); } Date date = new Date(l); SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String date_string = sd.format(date); try { super.pageContext.getOut().print(date_string); } catch (IOException e) { e.printStackTrace(); } return super.doStartTag(); } }
2、tld文件,放在WEB-INF下面
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN" "http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd"> <taglib> <tlib-version>1.0</tlib-version> <jsp-version>1.2</jsp-version> <short-name>ct</short-name> <uri>/dateConvert</uri> <tag> <name>longStr</name> <tag-class>com.TestTag</tag-class> <body-content>JSP</body-content> <attribute> <name>longtime</name> <required>true</required> <rtexprvalue>true</rtexprvalue> </attribute> </tag> </taglib>
3、web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5"> <jsp-config> <taglib> <taglib-uri>/dateConvert</taglib-uri> <taglib-location>dateConvert.tld</taglib-location> </taglib> </jsp-config> </web-app>
4/jsp引用
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%> <%@ taglib uri="/dateConvert" prefix="ct"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'index.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body><ct:longStr longtime="1314842011312"></ct:longStr> </body> </html>