package mytag; import java.util.*; import java.io.IOException; import java.text.*; import javax.servlet.jsp.JspException; import javax.servlet.jsp.tagext.TagSupport; public class MyTag extends TagSupport { String format = null; public String getFormat() { return format; } public void setFormat(String format) { this.format = format; } @Override public int doEndTag() throws JspException { // TODO Auto-generated method stub SimpleDateFormat sf = null; if (format.equals("date")) { sf = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss z"); try { pageContext.getOut().print(sf.format(new Date())); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else if (format.equals("time")) { sf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); try { pageContext.getOut().print(sf.format(new Date())); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return EVAL_PAGE; } @Override public int doStartTag() throws JspException { // TODO Auto-generated method stub return SKIP_BODY; } }
在WEB-INF目录中建立一个子目录 名字为taglib 在目录中创建tld文件
mytag.tld
<?xml version="1.0" encoding="ISO-8859-1" ?> <!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-version>1.2</jsp-version> <short-name>simple</short-name> <uri>http://www.zhao.com/mytag</uri> <description> A simple tab library for the examples </description> <tag> <name>mytag</name> <tag-class>mytag.MyTag</tag-class> <description> Display JSP sources </description> <attribute> <name>format</name> <required>true</required> <rtexprvalue>true</rtexprvalue> </attribute> </tag> </taglib>
新建一个jsp页面进行测试<%@ page language="java" contentType="text/html; charset=GBK" pageEncoding="GBK"%> <%@taglib prefix="mytag" uri="http://www.zhao.com/mytag" %> <!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=GBK"> <title>Insert title here</title> </head> <body> <mytag:mytag format="date"></mytag:mytag> </body> </html>
自定义标签的实践
最新推荐文章于 2024-08-10 07:22:37 发布