What is Servlet Listener

Servlet Listener is component which is comes into the picture when event occurs in the web application . Servlet Listener is used for listening to events in a web containers, such as when you create a session, or place an attribute in an session,request, application is up and down,

Different Listeners in Servlet :-

  javax.servlet.ServletContextListener - Interface for receiving notification events when server starts and stops.

 javax.servlet.ServletContextAttributeListener - Interface for receiving notification events when attributes are added or removed to the ServletContext.

  javax.servlet.ServletRequestListener -Interface for receiving notification events about requests coming into and going out of scope of a web application..

  javax.servlet.ServletRequestAttributeListener - Interface for receiving notification events when attributes are added or removed to the ServletRequest.

  javax.servlet.http.HttpSessionListener - Interface for receiving notification events when HttpSession object is created or destroyed.

  javax.servlet.http.HttpSessionBindingListener - Causes an object to be notified when it is bound to or unbound from a session scope.

 javax.servlet.http.HttpSessionAttributeListener- Interface for receiving notification when attributes are added or removed to the session scope.


 Servlet Listener Example code :-

servlet-context-listener

In above example we have created a ConnectionListener by implementing ServletContextListener , which is responsible for creating a connection to the database at the time of deploying the application means before serving any request to the client. We are setting or adding this connection in ServletContext (application scope) so that it can be shared across the whole application. ServletContextListener has two method declarations which are contextInitialized(), contextDestroy() to expose the event to the programmer.