Sunday, April 29, 2007

Creating Custom Tag Actions For JSPs

Custom tags are used to extend the JSTL, and are especially important when you decide to go scriptless in JSPs like I recently did. The process involves three actions: creating the tag handler class, creating the tag library descriptor (TLD), and updating the deployment descriptor (web.xml). This example creates a custom action that can be used in JSP pages to format dates for display in the resulting HTML.
The example is done in the NetBeans 5.5 IDE (with Sun Java System Application Server 9u1). NetBeans makes this process a no-brainer. I still encourage you to learn to write these tags by hand - for debugging and troubleshooting. Almost all Java web-oriented IDEs have similar features.

Create the Tag Library Descriptor (TLD):
- This is where your application looks up references to tags used in JSPs. It can refer to individual tag files or other libraries.
  1. Open the web application you want to add custom tags to in NetBeans IDE.
  2. Right-click web module | New - File/Folder - Web - Tag Library Descriptor, click Next | provide a name and prefix. Click Finish.
  3. A basic TLD is created. I normally remove the uri tag and commented text from the generated TLD file - keep things tidy.

Creating the Tag Handler Class:
- This is where what the tag does is defined. It follows JavaBean conventions and implements tag extension interfaces (such as SimpleTag in JSP 2.0).
  1. Open the web application you want to add custom tags to in NetBeans.
  2. Right-click web module | New - File/Folder - Web - Tag Handler, click Next | provide a name and package. Click Next. Provide the path to the TLD file we just made above to have its information added automatically. Provide attributes on the same page.
  3. The TLD is updated and the handler class created, complete with setters for all the attributes you specify. Only thing you need to do is modify the doTag() method with what you want the tag to do.
Updating the Deployment Descriptor (web.xml):
- Unfortunately, the IDE does not update web.xml (and you need to if you are not using JSP 2.x).
- You have to manually add the tag-lib node under jsp-config.
- With Java EE 5, you do not need to do this step.

Use the Custom Action in a JSP:
  1. Reference the TLD using the taglib page directive. Remember you can use Ctrl+Space in NetBeans to have the some of the directive's fields autocompleted for you.
  2. Use the tag to format some dates.
Source code with snippets for the example can be viewed in my published GoogleDocs. As you can see, adding custom tags is a trivial activity, made even easier by improvements in the JSP container since JSP 2.0.