class文件:
package com.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; //接收格式化模板(与tld中属性的名称保持一致)
@Override
public int doStartTag() throws JspException {
SimpleDateFormat sdf = new SimpleDateFormat(this.format);
try {
//输出格式化后的日期
super.pageContext.getOut().write(sdf.format(new Date()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return TagSupport.SKIP_BODY;
}
public String getFormat() {
return format;
}
public void setFormat(String format) {
this.format = format;
}
}
tld文件中的代码:
<?xml version="1.0" encoding="UTF-8"?>
<taglib version="2.1" 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 web-jsptaglibrary_2_1.xsd">
<tlib-version>1.0</tlib-version>
<short-name>datetag</short-name>
<tag>
<name>date</name>
<tag-class>
com.tag.DateTag
</tag-class>
<body-content>empty</body-content>
<attribute>
<name>format</name> <!-- format为属性名 -->
<required>true</required> <!-- 表示此值必须 -->
<rtexprvalue>true</rtexprvalue> <!-- 表示属性值是请求时表达式的结果(是否支持表达式输出) -->
</attribute>
</tag>
</taglib>
xml中tld文件路径的映射
<taglib>
<taglib-uri>mldn_date</taglib-uri>
<taglib-location>/WEB-INF/date.tld</taglib-location>
</taglib>
jsp文件:
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib prefix="mytag" uri="mldn_date" %>
<%
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 'datetag.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>
<h1><mytag:date format="yyyy-MM-dd HH:mm:ss.SSS"/></h1>
</body>
</html>