一、DateTag.java
package com.etecha.api.tagdemo;
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;
// 接收格式化模板
public int doStartTag() throws JspException
{
SimpleDateFormat sdf = new SimpleDateFormat(this.format);
try
{
super.pageContext.getOut().write(sdf.format(new Date()));
}
catch (Exception 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/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"
version="2.0">
<tlib-version>1.0</tlib-version> <!-- 表示标签库的版本 -->
<short-name>datetag</short-name> <!-- 为标签库在 TLD 中的描述名称-->
<tag>
<name>date</name> <!-- 表示标签在 JSP 中使用的名称 -->
<tag-class>com.etecha.api.tagdemo.DateTag</tag-class> <!-- 表示标签体所指向的 class 文件-->
<body-content>empty</body-content> <!-- 表示标签体内容为空 -->
<attribute>
<name>format</name> <!-- format 为属性名 -->
<required>true</required> <!-- 表示此值必须设置 -->
<rtexprvalue>true</rtexprvalue> <!-- 表示属性值是请求时表达式的结果 -->
</attribute>
</tag>
</taglib>
三、web.xml 配置:
<jsp-config>
<taglib>
<taglib-uri>etecha_date</taglib-uri>
<taglib-location>/WEB-INF/datetag.tld</taglib-location>
</taglib>
</jsp-config>
四、datetag.jsp
<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="mytag" uri="etecha_date" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/htmll; charset=UTF-8" />
<title>第一个标签库</title>
</head>
<body>
<h1><mytag:date format="yyyy-MM-dd HH:mm:ss:SSS" /></h1> <!-- 访问标签 -->
</body>
</html>