欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

JSP自定义标签

程序员文章站 2022-06-08 23:12:00
...
创建自定义标签分以下几步:

1. 扩展javax.servlet.jsp.tagext.TagSupport类并编译打包到WEB-INF/lib目录

2. 编写标签的tld文件

3. 在web.xml中指定tld文件(如果把tld文件放到自定义标签的jar包中,该步可以省略)

4. 在jsp中调用该标签


[size=small]1. 创建com.john.jsp.tags.MyFirstTag类:[/size]

需要添加对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目录下。

[size=small]2. 编写firstag.tld文件:[/size]


<?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>


[size=small]3. 在web.xml中添加:[/size]


<jsp-config>
<taglib>
<taglib-uri>http://czj4451.iteye.com/firsttag</taglib-uri>
<taglib-location>/WEB-INF/tlds/firsttag.tld</taglib-location>
</taglib>
</jsp-config>


[size=small]4. 创建tag.jsp:[/size]


<%@ taglib uri="http://czj4451.iteye.com/firsttag" prefix="firsttag" %>

<firsttag:myfirsttag/>