Overview of Java Web Technologies, Part 2 - Writing and Using Tags (
Page 9 of 10 )
Writing a Tag Library Descriptor (TLD)
A TLD is an XML document that describes a tag library. A TLD is validated against a DTD file. Currently, the latest version of the DTD is 1.2. A TLD must begin with the following header:
<?xml version="1.0" encoding="ISO-8859-1" ? >
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag
Library 1.2//EN"
"http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">
The root element of a TLD file is <taglib>. The subelements for the taglib element are as follows:
<!ELEMENT taglib (tlib-version, jsp-version, short-name, uri?,
display-name?, small-icon?, large-icon?, description?, validator?,
listener*, tag+) >
A taglib element must have the following elements:
- The tlib-version element specifies the version of the tag library implementation.
- The jsp-version element defines the JSP version that the tag library can work with.
- The short-name element encloses a unique name for the tag library.
- The tag element specifies a custom tag in the library. Its subelements are as follows:
<!ELEMENT tag (name, tag-class, tei-class?, body-content?,
display-name?, small-icon?, large-icon?, description?, variable*,
attribute*, example?) >
The other subelements are optional. You can read the description of each element in the DTD file downloadable from http://java.sun.com/dtd/web-jsptaglibarary_1_2.dtd.
Using a Custom Tag in a JSP Page
To use a custom tag in a JSP page, you need to be familiar with the taglib directive in JSP. A taglib directive has the following syntax:
<%@ taglib uri="tagLibraryURI" prefix="tagPrefix" %>
The uri attribute specifies an absolute or relative URI that uniquely identifies the TLD associated with this prefix. The prefix attribute defines a string that will become the prefix to distinguish a custom action.
With a taglib directive, you can use a custom tag of the following format for a custom tag that does not have a content body:
<prefix:tagName/>
Or, you can use the following format for a custom tag that has a content body:
<prefix:tagName>body</prefix:tagName>
You can pass attributes to the tag handler by specifying the attributes in the custom tag, each with the following format:
attributeName
="attributeValue"
The following example is a custom tag whose prefix is m and whose name is myTag. The tag has two attributes: number, with a value of 12, and power, with a value of 13.
<m:myTag number="12" power="13"/>
Note that an attribute value must be enclosed in quotation marks.