创建自定义标签分以下几步:
1. 扩展javax.servlet.jsp.tagext.TagSupport类并编译打包到WEB-INF/lib目录
2. 编写标签的tld文件
3. 在web.xml中指定tld文件(如果把tld文件放到自定义标签的jar包中,该步可以省略)
4. 在jsp中调用该标签
1. 创建com.john.jsp.tags.MyFirstTag类:
需要添加对jsp-api-[version number]-glassfish-[version number].[version time].jar的引用
public class MyFirstTag extends TagSupport {
@Override
public int doStartTag() throws JspException {
JspWriter writer = pageContext.getOut();
try {
writer.println("Hello world!");
} catch (IOException e) {
e.printStackTrace();
}
return SKIP_BODY;
}
}
编译并打包成jar文件放到WEB-INF/lib目录下。
2. 编写firstag.tld文件:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN" "web-jsptaglibrary_1_2.dtd">
<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>1.2</jsp-version>
<short-name>Significant</short-name>
<!-- It's acceptable to define the uri within the web.xml, the uri is unnecessarily reachable but necessarily unique -->
<uri>http://czj4451.iteye.com/firsttag</uri>
<tag>
<name>myfirsttag</name>
<!-- The full class name is case-sentitive -->
<tag-class>com.john.jsp.tags.MyFirstTag</tag-class>
</tag>
</taglib>
3. 在web.xml中添加:
<jsp-config>
<taglib>
<taglib-uri>http://czj4451.iteye.com/firsttag</taglib-uri>
<taglib-location>/WEB-INF/tlds/firsttag.tld</taglib-location>
</taglib>
</jsp-config>
4. 创建tag.jsp:
<%@ taglib uri="http://czj4451.iteye.com/firsttag" prefix="firsttag" %>
<firsttag:myfirsttag/>