编写一个继承自SimpleTagSupport的Java类:
import javax.servlet.jsp.tagext.SimpleTagSupport;public class HelloTag extends SimpleTagSupport{ }重写该类的doTag方法,在其中添加处理逻辑:
import javax.servlet.jsp.JspException;import javax.servlet.jsp.JspWriter;import javax.servlet.jsp.PageContext;import javax.servlet.jsp.tagext.SimpleTagSupport;public class HelloTag extends SimpleTagSupport{ private String info; private int qty; public void setInfo(String info) { this.info = info; } public void setQty(int qty) { this.qty = qty; } @Override public void doTag() throws JspException, IOException { PageContext ctx =(PageContext)getJspContext(); JspWriter out = ctx.getOut(); for(int i=0;i< qty;i++){ out.println(info+"<br/>"); } } }在WEB-INF下面新建一个tld文件,用于配置标签说明文件。代码如下:
<?xml version="1.0" encoding="UTF-8" ?><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 http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd" version="2.0"><tlib-version>1.1</tlib-version><short-name>c1</short-name><uri>http://www.tarena.com.cn/mytag</uri><tag> <name>hello</name> <tag-class>tag.HelloTag</tag-class> <body-content>empty</body-content> <attribute> <name>info</name> <required>true</required> <rtexprvalue>false</rtexprvalue> </attribute> <attribute> <name>qty</name> <required>true</required> <rtexprvalue>true</rtexprvalue> </attribute></tag></taglib>标签在页面中被引用时的代码如下:
<%@taglib uri="http://www.tarena.com.cn/mytag" prefix="c1" %//… …<c1:hello info="hello kitty" qty="${1+5}"/>容器依据JSP页面中的uri找到tld文件(依据标签中的<c1:hello>hello这个名字找到标签类tag.HelloTag。接下来实例化该标签,同时属性值赋给参数,调用doTag方法。