Jsp Tag
package tags; import java.util.Collection; import java.util.Iterator; import javax.servlet.jsp.JspException; import javax.servlet.jsp.tagext.TagSupport; public class IteratorTag extends TagSupport { private String var; private Collection items; private Iterator iter; public String getVar() { return var; } public void setVar(String var) { this.var = var; } public Collection getItems() { return items; } public void setItems(Collection items) { this.items = items; } @Override public int doStartTag() throws JspException { iter=items.iterator(); if(iter.hasNext()){ this.pageContext.setAttribute(var, iter.next()); return this.EVAL_BODY_INCLUDE; } return this.SKIP_BODY; } @Override public int doAfterBody() throws JspException { if(iter.hasNext()){ this.pageContext.setAttribute(var, iter.next()); return this.EVAL_BODY_AGAIN; } return this.SKIP_BODY; } }
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN" "http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd"> <taglib> <tlib-version>1.0</tlib-version> <jsp-version>1.2</jsp-version> <short-name>custom_dt</short-name> <uri>/myCustomTags</uri> <display-name>我的自定义</display-name> <description>这是我的自定义标签,用于测试</description> <tag> <name>MyIteratorTag</name> <tag-class>tags.IteratorTag</tag-class> <body-content>JSP</body-content> <display-name>测试的</display-name> <description>自定义的迭代标签</description> <attribute> <name>var</name> <required>true</required> <rtexprvalue>false</rtexprvalue> <description>变量名</description> </attribute> <attribute> <name>items</name> <required>true</required> <rtexprvalue>true</rtexprvalue> <description>用于iterate的集合</description> </attribute> </tag> </taglib>