学习地址:http://java.sun.com/developer/technicalArticles/xml/WebAppDev3/
最近要开发java的CMS 系统 只好逼着自己学了,很重要的一部分是自定义标签。研究了一下,还不算太难。
总述:包括 Bodyless Tags 和 Tags with a Body。
1. Develop the Tag Handler
Sample 1: Tag.java
public interface Tag { public final static int SKIP_BODY = 0; public final static int EVAL_BODY_INCLUDE = 1; public final static int SKIP_PAGE = 5; public final static int EVAL_PAGE = 6; void setPageContext(PageContext pageContext); void setParent(Tag parent); Tag getParent(); int doStartTag() throws JspException; int doEndTag() throws JspException; void release(); } |
实现接口或者继承一个已有的类TagSupport,
Sample 2: HelloTag.java
package tags; import java.io.*; import javax.servlet.jsp.*; import javax.servlet.jsp.tagext.*; public class HelloTag implements Tag { private PageContext pageContext; private Tag parent; public HelloTag() { super(); } public int doStartTag() throws JspException { try { pageContext.getOut().print( "This is my first tag!"); } catch (IOException ioe) { throw new JspException("Error: IOException while writing to client" + ioe.getMessage()); } return SKIP_BODY; } public int doEndTag() throws JspException { return SKIP_PAGE; } public void release() { } public void setPageContext(PageContext pageContext) { this.pageContext = pageContext; } public void setParent(Tag parent) { this.parent = parent; } public Tag getParent() { return parent; } } |
2. Create a Tag Library Descriptor
Sample 3: mytaglib.tld
<?xml version="1.0" encoding="ISO-8859-1" ?> <!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.// DTD JSP Tag Library 1.1//EN" "http://java.sun.com/j2ee/dtds/ web-jsptaglibrary_1_1.dtd"> <!-- a tag library descriptor --> <taglib> <tlibversion>1.0</tlibversion> <jspversion>1.1</jspversion> <shortname>first</shortname> <uri></uri> <info>A simple tab library for the examples</info> <tag> <name>hello</name> <tagclass>tags.HelloTag</tagclass> <bodycontent>empty</bodycontent> <info>Say Hi</info> </tag> </taglib>
|