自定义标签的实现由两部分组成:标签库描述文件、标签处理类;
1.在WEB-INF目录下创建name.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 web-jsptaglibrary_2_0.xsd" version="2.0"> <tlib-version>1.0</tlib-version> <short-name>mytaglib</short-name> <!-- 定义该标签库的URI 必须可以空--> <uri></uri> <!-- 定义第一个标签 --> <tag> <!-- 定义标签名 --> <name>field</name> <!-- 定义标签处理类 --> <tag-class>org.lxh.taglib.FieldTag</tag-class> <!-- 定义标签体为空 --> <body-content>empty</body-content> <attribute> <name>field</name> <required>true</required> <rtexprvalue>true</rtexprvalue> </attribute> <attribute> <name>count</name> <rtexprvalue>true</rtexprvalue> <retuired>true</retuired> </attribute> </tag> </taglib>
2.编写tag对应的class类即标签处理类
public class FieldTag extends TagSupport { private static final long serialVersionUID = -3282476920723218742L; private String field; private Integer count; public final String getField() { return field; } public final void setField(String field) { this.field = field; } public final Integer getCount() { return count; } public final void setCount(Integer count) { this.count = count; } @Override public int doEndTag() throws JspException { try { JspWriter out = pageContext.getOut(); out.print(field); out.print(count); } catch (IOException e) { e.printStackTrace(); } return super.doEndTag(); } }jsp引用:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@taglib prefix="tf" uri="/WEB-INF/tld/testfield.tld" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <% Integer a = 10; %> <tf:field field="hi" count="<%=a%>"/> </body> </html>