自定義標籤的實踐

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>






發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章