Using a Listener in a Tag Library

In Chapter 19, I described how to implement various types of listener components, as specified by the Servlet API: servlet context, session and request lifecycle event listeners, session attribute modification listeners, and session activation and passivation event listeners.

If you develop custom actions that interact with a listener in some way (for instance, an action that shows the current number of active sessions maintained by the session lifecycle event listener described in Chapter 19), you can bundle the event listener with your tag library. To get the listeners registered, you just define the listener implementation classes in the TLD for your library using the <listener> element (placed after the <validator> element):

<taglib ...>
  ...
  <listener> 
    <listener-class>
      com.ora.jsp.servlets.SessionCounterListener
    </listener-class> 
  </listener>
  ...
</taglib>

When the container loads the web application, it looks through all TLDs for listener definitions and registers all listeners it finds.

You can use listeners for a number of tasks. For instance, a servlet context lifecycle event listener can initialize resources used by the custom actions in the library (such as a connection pool) when the application starts and shut them down gracefully when it stops. A session lifecycle listener can initialize new sessions or keep track of the number of active sessions.

Get JavaServer Pages, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.