A servlet can be designated as an event listener. This enables the servlet to be notified when some external event or change 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, it is often useful to know whether a session became invalid because the Web server timed out the session or because a Web component within the application called the invalidate() method.
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 ServletContextListener (see Listing 12.11) 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 listener class in the Servlets application.
1. |
Add a new Web component to the Servlets application. On the component page, check the Event Listeners box to indicate that this is an event listener class (see Figure 12.22). As with a filter, there is no need to give the listener servlet a component alias because it is not called directly. Figure 12.22. deploytool Choose Component Type—Event Listeners. |
2. |
With the Servlets application highlighted in the left window, select the Event Listeners tab (see Figure 12.23). Figure 12.23. deploytool Event Listeners. |
3. |
Add the Listener class to the event listeners (see Figure 12.24). Figure 12.24. deploytool Event Listeners.The following will then be added to the Servlets deployment descriptor: <listener> <listener-class>Listener</listener-class> </listener> |
4. |
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.12).
3.146.37.250