開發和使用JSP自定義標籤過程:
1.開發標籤實現類.
HelloTag_Interface.java文件內容:
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.JspException;
import java.io.*;
import javax.servlet.jsp.JspTagException;
/**
* 以實現Tag接口的方式來開發標籤程序
*/
public class HelloTag
implements Tag {
private PageContext pageContext;
private Tag parent;
public HelloTag(){
super();
}
/**
* 設置標籤的頁面上下文
* @param pageContext
*/
public void setPageContext(PageContext pageContext) {
this.pageContext=pageContext;
}
/**
* 設置上一級標籤
* @param t
*/
public void setParent(Tag parent) {
this.parent=parent;
}
public Tag getParent() {
return this.parent;
}
/**
* 開始標籤時的操作
* @return
* @throws JspException
*/
public int doStartTag() throws JspException {
return this.SKIP_BODY;//返回SKIP_BODY,表示不計算標籤體
}
/**
* 結束標籤時的操作
* @return
* @throws JspException
*/
public int doEndTag() throws JspException {
try {
pageContext.getOut().write("Hello World!");
}
catch (IOException ex) {
throw new JspTagException("IO Error:"+ex.getMessage());
}
return this.EVAL_PAGE;
}
/**
* Release 用於釋放標籤程序佔用的資源,比如使用了數據庫連接,那麼應該關閉這個連接
*/
public void release() {
}
}
2.編寫標籤庫描述.
在WEB-INF/目錄下新創建一個mytag.tld文件:
<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 web-jsptaglibrary_2_0.xsd"
version="2.0">
<description>A tag library exercising SimpleTag handlers.</description>
<tlib-version>1.0</tlib-version>
<short-name>my</short-name>
<uri>/mytag</uri>
<description>學習標籤</description>
<tag>
<description>輸出Hello World</description>
<name>hello</name>
<tag-class>HelloTag</tag-class>
<body-content>empty</body-content>
</tag>
</taglib>
3.配置自定義標籤到工程中.
在web.xml文件裏添加:
...
<taglib>
<taglib-uri>/mytag</taglib-uri>
<taglib-location>/WEB-INF/mytag.tld</taglib-location>
</taglib>
...
</web-app>
4.在JSP文件中使用自定義標籤.
編寫mytag.jsp文件:
<%@ page contentType="text/html;charset=GBK" language="java" %>
<html>
<head>
<title>first tag</title>
<meta http-equiv="Content-Type" content="text/html;charset=GBK">
</head>
<body>
<p>以下的內容從Taglib中輸出顯示:</p>
<p><my:hello></p>
</body>
</html>