April 20, 2010

Creating a simple JSP Tag File

This is a simple tutorial for creating a very basic Tag File for use in Java Web Applications:

A Tag File (*.tag), is a way for non-Java developers to build custom tags without writing a Java class (eg. a Custom Tag Handler class).

Step 1

Create the file coolimage.jsp with the following content:

  <%@ attribute name="imageName" required="true" rtexprvalue="true"/>
   Here is a cool image: <img src="images/doggy.png" imageName="${imageName}">

Step 2

Rename the file coolimage.jsp to coolimage.tag and put it under: WEB-INF/tags/coolimage.tag

Step 3

Create the test.jsp page which will use the Tag File:

<%@ taglib prefix="myTags" tagdir="/WEB-INF/tags" %>

<myTags:coolImage imageName="My Favorite Doggy"/>

Step 4

Don't forget to add doggy.png to your webapp/images folder.

If everything worked well, you have now just created a simple JSP Tag File.

Things to keep in mind when creating Tag Files

To make sure the Servlet Container finds your Tag File place your *.tag file in file(s) any of these locations:

  • WEB-INF/tags/
  • WEB-INF/lib/mylibrary.jar -> META-INF/tags/ //inside the META-INF folder of your jar file

Using a Tag File inside a jar file

If you have a Tag File inside a jar library, it must have a an appropriate entry in a TLD file.

The TLD file you will need in this case is similar, but not the same as the TLD file which declares a Custom Tag (See my other tutorial on Custom Tags). It only specifies the location of the Tag File (not it's functionality) so the container can find it.

The TLD file you will need in this case will look something like this: