之前我们使用的标签库都是JSTL为我们提供的,大部分的数据操作和控制都可以使用它来完成,但是如果我们项目中有特殊需求或者为了统一开发规范,那么我们也可以自己定义一套标签库供自己的团队使用。
在web.xml文件中配置元素(可选,如果标签库描述文件不放在WEB-INF或其子目录下则需要配置)
在JSP文件中使用taglib指令引入标签库
自定义的tag文件是位于/WEB-INF/tags目录或其子目录中的.tag或者.tagx文件。我们自己web app的tag文件可以被TLD文件通过
<%@ taglib prefix="myTag" tagdir="/WEB-INF/tags" %>
<%@ taglib prefix="t" tagdir="/WEB-INF/tags/fmt" %>
<%@ taglib prefix="f" tagdir="/WEB-INF/tags/fn" %>
三者的区别是是其相应的tag名字分别是
如果我们要封装为jar包,作为第三方的tag文件提供,则tag文件需要在jar文件的/META-INF/tags目录下,且通过JAR文件的/META-INF目录下的TLD文件所使用。除了与tld文件路径有区别外,不能以tag文件的方式被直接使用。
这是JSTL采用的方式。TLD(Tag Library Descriptor)描述tag和function,以及具体执行的java代码tag handler(查看jstl jar包META-INF下tld文件)。Tag Handler是javax.servlet.jsp.tagext.Tag或javax.servlet.jsp.tagext.SimpleTag的实现。web容器使用TLD将jsp中的tag映射到执行的java代码。前面的博客已介绍了jstl标签的使用,我们来看看这些TLD是怎么写的。
<taglib xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd"
version="2.1">
<description>JSTL 1.1 core librarydescription>
<display-name>JSTL coredisplay-name>
<tlib-version>1.1tlib-version>
<short-name>cshort-name>
<uri>http://java.sun.com/jsp/jstl/coreuri>
......
taglib>
这里是XML的标准声明,通过Schema在web-jsptaglibrary_2_1.xsd中定义,TLD文件标签的先后顺序都是通过schema约束。描述TLD的整体信息:
<validator>
<description>
Provides core validation features for JSTL tags.
description>
<validator-class>
org.apache.taglibs.standard.tlv.JstlCoreTLV
validator-class>
validator>
在编译的时候使用javax.servlet.jsp.tagext.TagLibraryValidator类来验证,确保正确使用tag lib,如&;
listener,如ServletContextListener,HttpSessionListener,但是它的使用极为罕见,反正我是没见过,略过。
Catches any Throwable that occurs in its body and optionally
exposes it.
<name>catchname>
class>org.apache.taglibs.standard.tag.common.core.CatchTag class>
JSP
Name of the exported scoped variable for the
exception thrown from a nested action. The type of the
scoped variable is the type of the exception thrown.
<name>varname>
false
false
<myTag:doSomething>
<jsp:attribute name="someAttribute">
Any <b>contentb> <fmt:message key="including.jsp.tags" />
jsp:attribute>
myTag:doSomething>
在tld中是可以使用0~n个tag文件,定义在tag标签后面,如下:
<tag-file>
<description>This tag outputs bar.description>
<name>fooname>
<path>/WEB-INF/tags/foo.tagpath>
tag-file>
若tag文件加入到jar中,就必须在TLD中定义;如果多个tag文件有相同的namespace,也需在TLD中定义。
<function>
<description>
Tests if an input string contains the specified substring.
description>
<name>containsname>
<function-class>org.apache.taglibs.standard.functions.Functionsfunction-class>
<function-signature>boolean contains(java.lang.String, java.lang.String)function-signature>
<example>
<c:if test="${fn:contains(name, searchString)}">
example>
function>