[ Team LiB ] Previous Section Next Section

Chapter 21. Developing Custom Tag Libraries Using Java

Custom actions let you encapsulate logic and make it available to page authors in a familiar format. Throughout this book, JSTL actions and a number of other custom actions are used for such tasks as accessing a database, including localized content, encoding URLs, and much more. Using these actions, the amount of Java code in your JSP pages can be kept to a minimum, making your application easier to debug and maintain. However, for complex applications, these generic actions may not be enough. Perhaps you want to develop business-specific actions to access the database instead of putting SQL statements in the JSP pages. You may want to present complex data as a set of nested HTML tables with cells formatted differently depending on their values. Instead of using JSTL conditional and loop actions in the JSP page to generate this table, an application-specific custom action can be used.

In Chapter 11, I showed you how to use tag files to implement custom actions. Tag files allow nonprogrammers to develop custom actions and are also suitable for custom actions that generate a lot of markup, such as HTML tables. But custom actions can also be implemented as Java classes, and that's the focus of this chapter. A Java implementation is a good choice for very complex actions or when you need to squeeze out every ounce of performance.

To develop a custom action as a Java class, you use a set of classes and interfaces referred to in the JSP specification as the tag extension mechanism. The class that implements the behavior of a custom action is called a tag handler class. It is basically a bean, with property setter methods corresponding to the custom action element's attributes, that also implements one of four Java interfaces defined as part of the tag extension mechanism.

JSP 2.0 introduces a new type of tag handler, represented by a single interface. A tag handler of this type is referred to as a simple tag handler. Tag handlers based on the three interfaces defined by JSP 1.1 and 1.2 are still supported and are now referred to as classic tag handlers. A simple tag handler can do everything a classic tag handler can but is a lot easier to implement. The only caveat is that the body of a custom action implemented as a simple tag handler cannot contain Java code (scripting elements). We'll look at the most common and simple aspects of both types in this chapter, starting with the simple tag handler, and then work through more advanced features in Chapter 22 and Chapter 23.

    [ Team LiB ] Previous Section Next Section