[ Team LiB ] Previous Section Next Section

Recipe 22.15 Adding a Listener Class to a Tag Library


You want to include a listener class with your tag library.


Add a listener element to your TLD file.


The servlet API includes "application event listeners," which are special Java classes that are notified by the web container when certain events occur, such as the creation of a new user session (see Chapter 11). You can include listener classes with your tag libraries. For example, you might have a session-related tag that needs to know when sessions are created or destroyed.

The listener element has exactly the same syntax as it may appear in the web.xml deployment descriptor. Example 22-11 shows a listener element included in a JSP Version 2.0 TLD.

Example 22-11. Adding a listener element to a JSP 2.0 TLD
<!-- beginning of the TLD file. The listener element is nested in the taglib element. SEE

<taglib xmlns="http://java.sun.com/xml/ns/j2ee" 
    <description>Cookbook custom tags</description>


    <!-- declare a tag here. See Example 22-2 (Recipe 22.2), Example 22-3 (recipe
     22.3), or 22-7 (Recipe 22.9) -->



The JSP specification requires the JSP container to automatically instantiate and register the listeners that are associated with tag libraries. A listener can be used with a tag library to track the number of requests the web application is receiving, as shown in the ServletRequestListener in Example 18-8 (Recipe 18.6).

JSP 1.2's TLD file uses an XML DTD. Therefore, the TLD elements must appear in a specific sequence. The listener element is nested inside the taglib element; listener appears after all of the other nested elements except for tag. You can precede your tag elements with the listener element. In the JSP 2.0 TLD, on the other hand, you can position the listener right after the taglib root element.

Store any listener classes in the same JAR file as the one containing any tag handler classes.

Make sure to specify the listener class in the listener-class element as a fully qualified class name, or the JSP container will probably have trouble finding the class.

See Also

Example 18-8 in Recipe 18.6 for an example of a class that implements the javax.servlet.ServletRequestListener; Chapter 11 and Chapter 14 for several listener-related recipes; Recipe 22.2 on creating a JSP 1.2 TLD file; Recipe 22.3 on creating a JSP 2.0 TLD; Recipe 22.9 on creating a TLD for a simple tag handler; the custom tag sections of Hans Bergsten's JavaServer Pages, Third Edition (O'Reilly).

    [ Team LiB ] Previous Section Next Section