Servlet Listener (web application listener)

  • During the lifetime of a typical web application, a number of events take place.

    • request objects are created and destroyed (response send).

    • session objects are created & destroyed (session invalidated or time out).

    • contexts(web apps) objects are created & destroyed (3 triggers of application's end of life).

    • request or session or context attributes are added, removed, or modified etc.

  • The Servlet API provides a number of listener interfaces that one can implement in order to react to these events.

    • Event Listener interface's sub interfaces

      1. ServletRequestListener

        • Interface for receiving notification events about requests coming into and going out of scope of a web application.

      2. HttpSessionListener

        • Interface for receiving notification events about HttpSession lifecycle changes.

      3. ServletContextListener

        • Interface for receiving notification events about ServletContext lifecycle changes.

  • Three ways of registering a web listener created by programmer.

    • The implementation class must be either declared in the deployment descriptor of the web application

    • Annotated with WebListener annotations,

    • Registered via one of the addListener methods defined on ServletContext.

Steps for creating a web listener

  1. Create a class, implementing from Listener i/f.

  2. Register it with WC through annotations or xml tags.

    • @WebListener annotation(class level).

    • XML tags in web.xml.

Last updated