Event Listening

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.

Table 12.6. Servlet Event Listener Interfaces
Listener InterfaceNotification
ServletRequestAttributeListenerWhen a request attribute is added, removed, or replaced
ServletRequestListenerWhen the processing of a request is started
HttpSessionAttributeListenerWhen a session attribute is added, removed, or replaced
HttpSessionListenerWhen a session is created, replaced, or destroyed
ServletContextAttributeListenerWhen a servlet context attribute is added, removed, or replaced
ServletContextListenerAbout changes to servlet context, such as context initialization or the context is to be shut down

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.

Listing 12.10. Servlet Listener to Initialize Counter
import javax.servlet.*;
import javax.servlet.http.*;

public class ServletListener extends HttpServlet
               implements ServletContextListener {

  private ServletContext context = null;

  public void contextInitialized(ServletContextEvent event) {
   context = event.getServletContext();

   Integer counter = new Integer(0);
   context.setAttribute("Counter", counter);
   context.log("Created Counter");
  }

  public void contextDestroyed(ServletContextEvent event) {
   event.getServletContext().removeAttribute("Counter");
  }
}

Deploying the Listener

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).

Listing 12.11. Amended AuditFilter.java Code Showing New doFilter() Method
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws
 IOException, ServletException {
  if (filterConfig == null)
    return;
  StringBuffer buf = new StringBuffer();
  buf.append ("The number of hits is: ");
  ServletContext ctx = filterConfig.getServletContext();
  synchronized (ctx) {
    Integer counter = (Integer)ctx.getAttribute("Counter");""
    counter = new Integer(counter.intValue() + 1);
    buf.append (counter.toString());
    filterConfig.getServletContext().log(buf.toString());
    filterConfig.getServletContext().setAttribute("Counter", counter);
  }
  chain.doFilter(req, res);
}

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.110.155