- 7.1 Tag Library Components
- 7.2 Example: Simple Prime Tag
- 7.3 Assigning Attributes to Tags
- 7.4 Example: Prime Tag with Variable Length
- 7.5 Including Tag Body in the Tag Output
- 7.6 Example: Heading Tag
- 7.7 Example: Debug Tag
- 7.8 Creating Tag Files
- 7.9 Example: Simple Prime Tag Using Tag Files
- 7.10 Example: Prime Tag with Variable Length Using Tag Files
- 7.11 Example: Heading Tag Using Tag Files
7.8 Creating Tag Files
JSP specification version 2.0 introduced a JSP-based way to create custom tags using tag files. One of the key differences between what we talk about in the beginning of this chapter, Java-based custom tags, and tag files (or JSP-based custom tags) is that with Java-based tags the tag handler is a Java class, whereas with JSP-based tags the tag handler is a JSP page. Tag files are also a bit simpler to write because they don't require you to provide a TLD.
The guidelines for when to develop a JSP-based custom tag versus a Java-based custom tag are analogous to the guidelines for when to use a JSP page versus a servlet. When there is a lot of logic, use Java to create output. When there is a lot of HTML formatting, use tag files to create output. To review the general benefits of JSPs versus servlets, please see Section 10.2 of Volume 1.
There is one caveat that might force your choice between tag files and Java-based custom tags. Tag files run only in JSP 2.0, whereas Java-based custom tags have a "classic" version that does not rely on the new SimpleTag API. So, if the container you are targeting is only compliant with earlier versions of the specification, you have to use classic Java-based custom tag development. The bad news is that classic Java-based custom tag development is quite more complicated than the SimpleTag API and we do not cover classic tags in this book. The good news is that almost all mainstream containers have been updated to be compliant with servlet specification 2.4 and JSP specification 2.0, so chances are you won't need to develop the classic Java-based custom tags.
In general, there are two steps to creating a JSP-based custom tag.
- Create a JSP-based tag file. This file is a fragment of a JSP page with some special directives and a .tag extension. It must be placed inside the WEB-INF/tags directory or a subdirectory thereof.
- Create a JSP page that uses the tag file. The JSP page points to the directory where the tag file resides. The name of the tag file (minus the .tag extension) becomes the name of the custom tag and therefore no TLD connecting the implementation of the tag with its name is needed.
In the next few sections, we reproduce the same custom tags we developed earlier in this chapter, but we use tag files to accomplish it.