一:自定义标签库(步骤)
1>开发自定义标签类(编写一个实现SimpleTagSupport接口的java类)html
package book07; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import javax.servlet.jsp.JspException; import javax.servlet.jsp.JspWriter; import javax.servlet.jsp.tagext.SimpleTagSupport; /** * @author 国真 * */ public class DateFormat extends SimpleTagSupport { /** * 若是标签类中包含属性,每一个属性都要有对应的setter和getter方法 */ Date date; String type; public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public String getType() { return type; } public void setType(String type) { this.type = type; } /** * 重写doTag()方法,该方法在标签结束生成页面内容 */ @Override public void doTag() throws JspException, IOException { SimpleDateFormat sdf = new SimpleDateFormat(); if(type.equals("full")){ sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); } if(type.equals("date")){ sdf = new SimpleDateFormat("yy-MM-dd"); } if(type.equals("time")){ sdf = new SimpleDateFormat("HH:mm:ss"); } //将格式化后的结果输出到页面 JspWriter out = super.getJspContext().getOut(); out.print(sdf.format(date)); } }
***2>创建TLD文件(在tld文件中对标签处理器类进行描述,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/j2ee/dtd/web-jsptaglibrary_1_2.dtd"> <taglib> <!--定义标签版本库--> <tlib-version>1.0</tlib-version> <!--定义jsp版本库--> <jsp-version>2.0</jsp-version> <short-name>dateFormat</short-name> <uri>/dateFormat</uri> <tag> <name>dateFormat</name><!-- tag的名字 --> <tag-class>book07.DateFormat</tag-class><!-- tag对应的java类的名字 --> <body-content>empty</body-content> <description>format date</description> <attribute> <!-- 这里表示的是这个tag的一个参数 --> <name>date</name> <!-- 这个参数的名字 --> <required>true</required> <!-- 是不是必填项 --> <rtexprvalue>true</rtexprvalue> <!-- 这个参数是否能够写入(这个参数是否能够动态赋值) --> </attribute> <attribute> <name>type</name> <required>true</required> <rtexprvalue>true</rtexprvalue> </attribute> </tag> </taglib>
***3>使用标签库(在JSP页面中导入和使用自定义标签)***
<%@page import="java.util.Date"%> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@taglib prefix="mydate" uri="/dateFormat" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>自定义日期标签</title> </head> <body> <mydate:dateFormat date="<%= new Date() %>" type="full"/> <br /> <mydate:dateFormat date="<%= new Date() %>" type="date"/> <br /> <mydate:dateFormat date="<%= new Date() %>" type="time"/> </body> </html>