Show TOC

Developing Event ListenersLocate this document in the navigation structure

Context

A listener can be used to monitor and react to events in a servlet's life cycle by defining methods that get invoked when life cycle events occur. In this way, you can keep track of events such as application context initialization or destruction, session creation, and so on, and can react accordingly to them.

Application event listeners are classes that implement one or more of the servlet event listener interfaces. Servlet event listeners support notification for state changes in the ServletContext and HttpSession objects, specifically:

  • Servlet context listeners are used to manage resources or state held at Virtual Machine level for the application.

  • HTTP session listeners are used to manage state or resources associated with a series of requests made in a Web application from the same client or user.

Procedure


  1. In the Project Explorer , select the Dynamic Web Project.

  2. In the context menu, choose NewListener .

  3. In the Create Listener wizard, enter the settings as required.

    Choose all types of life cycle events you want to handle. Each event type is associated with one of the servlet event listener interfaces. The following table summarizes events and their corresponding listeners.

    Event types and their corresponding listeners

    Scope of Event

    Event

    Event Type

    Event Interface

    ServletContext

    Initialization or destruction of a servlet context

    ServletContextEvent

    ServletContextListener

    ServletContext

    Context attribute(s) added, removed or replaced

    ServletContextAttributeEvent

    ServletContextAttributeListener

    Session

    Session created or destroyed

    HttpSessionEvent

    HttpSessionListener

    Session

    Session attribute(s) added, removed or replaced

    HttpSessionBindingEvent

    HttpSessionAttributeListener

    Session

    Session activated or passivated

    HttpSessionEvent

    HttpSessionActivationListener

    Session

    The current object is bound or unbound to a session

    HttpSessionBindingEvent

    HttpSessionBindingListener

    Servlet Request

    Request comes in and out of scope in the Web component

    ServletRequestEvent

    ServletRequestListener

    Servlet Request

    Request attribute(s) added, removed or replaced

    ServletRequestAttributeEvent

    ServletRequestAttributeListener

  4. Choose Finish .

Results

The skeleton of the listener class is created. You can now implement the class body as necessary.

The listener is automatically added to the web.xml of the Dynamic Web Project.