The Java EE 6 Tutorial, Volume I

Handling Servlet Life-Cycle Events

You can monitor and react to events in a servlet’s life cycle by defining listener objects whose methods get invoked when life-cycle events occur. To use these listener objects you must define and specify the listener class.

Defining the Listener Class

You define a listener class as an implementation of a listener interface. Table 10–1 lists the events that can be monitored and the corresponding interface that must be implemented. When a listener method is invoked, it is passed an event that contains information appropriate to the event. For example, the methods in the HttpSessionListener interface are passed an HttpSessionEvent, which contains an HttpSession.

Table 10–1 Servlet Life-Cycle Events



Listener Interface and Event Class 

Web context (see Accessing the Web Context)

Initialization and destruction 

javax.servlet.ServletContextListener and


Attribute added, removed, or replaced 

javax.servlet.ServletContextAttributeListener and


Session (See Maintaining Client State)

Creation, invalidation, activation, passivation, and timeout 

javax.servlet.http.HttpSessionListener, javax.servlet.http.HttpSessionActivationListener, and


Attribute added, removed, or replaced 

javax.servlet.http.HttpSessionAttributeListener and



A servlet request has started being processed by web components 

javax.servlet.ServletRequestListener and


Attribute added, removed, or replaced 

javax.servlet.ServletRequestAttributeListener and


Specifying Event Listener Classes

You specify an event listener class using the listener element of the deployment descriptor.

    You can specify an event listener using the deployment descriptor editor of NetBeans IDE by doing the following:

  1. Expand your application’s project node.

  2. Expand the project’s Web Pages and WEB-INF nodes.

  3. Double-click web.xml.

  4. Click General at the top of the web.xml editor.

  5. Expand the Web Application Listeners node.

  6. Click Add.

  7. In the Add Listener dialog, click Browse to locate the listener class.

  8. Click OK.