定义一个日期标签,则用户就必须指定格式化日期的格式;
DateTag:
package com.keith.tag;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;
public class DateTag extends TagSupport {
// 接受格式化模板
private String format;
@Override
public int doStartTag() throws JspException {
SimpleDateFormat sdf = new SimpleDateFormat();
try {
super.pageContext.getOut().write(sdf.format(new Date()));
} catch (IOException e) {
e.printStackTrace();
}
return TagSupport.SKIP_BODY;
}
public String getFormat() {
return format;
}
public void setFormat(String format) {
this.format = format;
}
}
datetag.tld:
<?xml version="1.0" encoding="UTF-8"?> <taglib xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd" version="2.1"> <!-- 标签库的版本 --> <tlib-version>1.0</tlib-version> <!-- 为标签苦在TLD中的描述名称 --> <short-name>datetag</short-name> <tag> <!-- 表示标签在JSP中的使用名称 --> <name>date</name> <!-- 表示这个标签所这项的Class --> <tag-class>com.keith.tag.DateTag</tag-class> <!-- 标签体内容为空 --> <body-content>empty</body-content> <attribute> <!-- format为属性名 --> <name>format</name> <!-- 表示此值必须设置 --> <required>true</required> <!-- 表示属性值是否支持表达式输出,如果设置成true,则可以通过EL,或者脚本输出 --> <rtexprvalue>true</rtexprvalue> </attribute> </tag> </taglib>
web.xml:
<taglib> <taglib-uri>date</taglib-uri> <taglib-location>/WEB-INF/datetag.tld</taglib-location> </taglib>
index.jsp:
<%@ taglib prefix="datetag" uri="date"%>
<body>
<datetag:date format="yyyy-MM-dd HH:mm:s.SSS"/>
</body>