A servlet can be designated as an event listener. This enables the servlet to be notified when a lifecycle event or a change to request or session attributes has occurred.
There are a number of listener interfaces that you can implement in your servlet. All the listener interfaces extend java.util.EventListener.
Table 12.6 provides a list of the listener interfaces.
The listener classes are often used as a way of tracking sessions within a Web application. For example, a listener could be setup to examine all the objects in a Session to determine if any action is required when the session times out or is invalidated. Such a listener could close open database connections or rollback partial transactions.
In the filter section, we incremented a counter each time the application was accessed. The servlet filter code had to check that the counter existed before incrementing it. The following servlet event listener ServletContextListener (see Listing 12.10) sets up the counter when the context is initialized before any request is processed. The ServletContextListener interface has two methods:
contextInitialized() This receives notification that the application is ready to process requests.
contextDestroyed() This is notified that the context is about to be shut down.
Go through the following steps to deploy the servlet listener class in the examples application:
1. | Add a new Web component to the application examples using the New Web Component Wizard as for a normal servlet. You do not need to specify an alias for a listener. |
2. | After adding the listener select your Web Application WAR file and on the Event Listeners page add a new row to the list of listeners. Select this row and choose ServletListener from the list of choices (see Figure 12.18). Figure 12.18. deploytool Event Listeners.The following will then be added to the Servlets deployment descriptor: <listener> <listener-class>ServletListener</listener-class> </listener> <servlet> <servlet-name>ServletListener</servlet-name> <servlet-class>ServletListener</servlet-class> </servlet> |
3. | Deploy the application. |
Because the listener initializes the counter to 0, and this is guaranteed to be called before any servlet code, you can now simplify the AuditFilter code and remove the check for a null counter (see Listing 12.11).
3.144.110.155