前面介绍了标签库的特点和标签库的组成,开发标签库主要有两个主要的步骤:开发标签库实现类和定义标签库定义文件(TLD文件)。在Struts 2框架中,提供了标签的处理实现类和标签库定义文件。
读者可以在struts2-core-2.0.11.jar压缩文件的META-INF目录下找到struts-tags.tld文件,如图9.2所示。

图9.2 Struts 2的标签库定义文件
struts-tags.tld是一个标准的XML文件,其内容片断如代码9.1所示。
代码9.1 struts-tags.tld内容片断
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN" "http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">
<taglib>
<tlib-version>2.2.3</tlib-version>
<jsp-version>1.2</jsp-version>
< -- 指定标签库默认的名称 -- >
<short-name>s</short-name>
< -- 指定标签库默认的URI -- >
<uri>/struts-tags</uri>
<display-name>"Struts Tags"</display-name>
<description><![CDATA["To make it easier to access dynamic data;
the Apache Struts framework includes a library of custom tags.
The tags interact with the framework's validation and internationalization features;
to ensure that input is correct and output is localized.
The Struts Tags can be used with JSP FreeMarker or Velocity."]]> </description>
< -- 定义标签action -- >
<tag>
<name>action</name>
<tag-class>org.apache.struts2.views.jsp.ActionTag</tag-class>
<body-content>JSP</body-content>
<description><![CDATA[Execute an action from within a view]]></description>
<attribute>
<name>executeResult</name>
<required>false</required>
<rtexprvalue>false</rtexprvalue>
<description><![CDATA[Whether the result of this action (probably a view) should be executed/rendered]]></description>
</attribute>
<attribute>
<name>flush</name>
<required>false</required>
<rtexprvalue>false</rtexprvalue>
<description><![CDATA[Whether the writer should be flush upon end of action component tag, default to true]]></description>
</attribute>
<attribute>
<name>id</name>
<required>false</required>
<rtexprvalue>false</rtexprvalue>
<description><![CDATA[id for referencing element. For UI and form tags it will be used as HTML id attribute]]></description>
</attribute>
<attribute>
<name>ignoreContextParams</name>
<required>false</required>
<rtexprvalue>false</rtexprvalue>
<description><![CDATA[Whether the request parameters are to be included when the action is invoked]]></description>
</attribute>
<attribute>
<name>name</name>
<required>true</required>
<rtexprvalue>false</rtexprvalue>
<description><![CDATA[Name of the action to be executed (without the extension suffix eg. .action)]]></description>
</attribute>
<attribute>
<name>namespace</name>
<required>false</required>
<rtexprvalue>false</rtexprvalue>
<description><![CDATA[Namespace for action to call]]></description>
</attribute>
</tag>
… …
如果需要在JSP页面中使用标签库,则需要使用<taglib-location…/>元素指定标签库定义文件(TLD)文件的位置。一个标准的使用Struts 2标签库的格式如下:
<%@ page contentType="text/html;charset=UTF-8" language="java"%>
<--导入Struts 2标签库-->
<%@ taglib prefix="s" uri="/struts-tags"%>
使用上面代码导入Struts 2框架的系统的标签库,其中s为标签库默认的短名,在JSP的标签使用中引用。
★ 注意 ★
如果开发者使用Servlet 2.3或者更早的规范时,需要在web.xml中增加标签库的定义,才能够在页面中使用taglib来导入标签库。