[ Team LiB ] |
![]() ![]() |
Recipe 22.15 Adding a Listener Class to a Tag LibraryProblemYou want to include a listener class with your tag library. SolutionAdd a listener element to your TLD file. DiscussionThe 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 CHAPTER 11 OR 14 FOR LISTENER CODE EXAMPLES --> <taglib xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation= "http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd" version="2.0" > <tlib-version>1.0</tlib-version> <jsp-version>2.0</jsp-version> <short-name>cbck</short-name> <uri>com.jspservletcookbook.tags</uri> <description>Cookbook custom tags</description> <listener> <listener-class> com.jspservletcookbook.ReqListener </listener-class> </listener> <tag> <!-- declare a tag here. See Example 22-2 (Recipe 22.2), Example 22-3 (recipe 22.3), or 22-7 (Recipe 22.9) --> </tag> </taglib> 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). Store any listener classes in the same JAR file as the one containing any tag handler classes.
See AlsoExample 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 ] |
![]() ![]() |