开发和使用JSP自定义标签过程:
import javax.servlet.jsp.tagext.Tag; 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() { } }
<?xml version="1.0" encoding="GBK"?> <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>
<web-app> ... <taglib> <taglib-uri>/mytag</taglib-uri> <taglib-location>/WEB-INF/mytag.tld</taglib-location> </taglib> ... </web-app>
<%@ taglib uri="/mytag" prefix="hello" %> <%@ 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>
原文地址:http://blog.csdn.net/leimengyuanlian/article/details/42299455