ServletContextListener Servlet Listener Example

Filed Under: Java EE

ServletContextListener is one of the many Servlet Listener we have. This is the fifth article in the series of Java Web Application, you might want to check out earlier four articles too.

  1. Java Web Application
  2. Servlets in Java
  3. Servlet Session Management
  4. Servlet Filter

Servlet Listener

ServletContextListener, servlet listener, servlet listener example, ServletContextListener example

In this tutorial, we will look into servlet listener, benefits of servlet listeners, some common tasks that we can do with listeners, servlet API listener interfaces and Event objects. In the end we will create a simple web project to show example of commonly used Listener implementation for ServletContext, Session and ServletRequest.

  1. Why do we have Servlet Listener?
  2. Servlet Listener Interfaces and Event Objects
  3. Servlet Listener Configuration
  4. Servlet Listener Example
  5. ServletContextListener
  6. ServletContextAttributeListener
  7. HttpSessionListener
  8. ServletRequestListener

  1. Why do we have Servlet Listener?

  2. We know that using ServletContext, we can create an attribute with application scope that all other servlets can access but we can initialize ServletContext init parameters as String only in deployment descriptor (web.xml). What if our application is database oriented and we want to set an attribute in ServletContext for Database Connection. If you application has a single entry point (user login), then you can do it in the first servlet request but if we have multiple entry points then doing it everywhere will result in a lot of code redundancy. Also if database is down or not configured properly, we won’t know until first client request comes to server. To handle these scenario, servlet API provides Listener interfaces that we can implement and configure to listen to an event and do certain operations.

    Event is occurrence of something, in web application world an event can be initialization of application, destroying an application, request from client, creating/destroying a session, attribute modification in session etc.

    Servlet API provides different types of Listener interfaces that we can implement and configure in web.xml to process something when a particular event occurs. For example, in above scenario we can create a Listener for the application startup event to read context init parameters and create a database connection and set it to context attribute for use by other resources.

  3. Servlet Listener Interfaces and Event Objects

  4. Servlet API provides different kind of listeners for different types of Events. Listener interfaces declare methods to work with a group of similar events, for example we have ServletContext Listener to listen to startup and shutdown event of context. Every method in listener interface takes Event object as input. Event object works as a wrapper to provide specific object to the listeners.

    Servlet API provides following event objects.

    1. javax.servlet.AsyncEvent – Event that gets fired when the asynchronous operation initiated on a ServletRequest (via a call to ServletRequest#startAsync or ServletRequest#startAsync(ServletRequest, ServletResponse)) has completed, timed out, or produced an error.
    2. javax.servlet.http.HttpSessionBindingEvent – Events of this type are either sent to an object that implements HttpSessionBindingListener when it is bound or unbound from a session, or to a HttpSessionAttributeListener that has been configured in the web.xml when any attribute is bound, unbound or replaced in a session.
      The session binds the object by a call to HttpSession.setAttribute and unbinds the object by a call to HttpSession.removeAttribute.
      We can use this event for cleanup activities when object is removed from session.
    3. javax.servlet.http.HttpSessionEvent – This is the class representing event notifications for changes to sessions within a web application.
    4. javax.servlet.ServletContextAttributeEvent – Event class for notifications about changes to the attributes of the ServletContext of a web application.
    5. javax.servlet.ServletContextEvent – This is the event class for notifications about changes to the servlet context of a web application.
    6. javax.servlet.ServletRequestEvent – Events of this kind indicate lifecycle events for a ServletRequest. The source of the event is the ServletContext of this web application.
    7. javax.servlet.ServletRequestAttributeEvent – This is the event class for notifications of changes to the attributes of the servlet request in an application.

    Servlet API provides following Listener interfaces.

    1. javax.servlet.AsyncListener – Listener that will be notified in the event that an asynchronous operation initiated on a ServletRequest to which the listener had been added has completed, timed out, or resulted in an error.
    2. javax.servlet.ServletContextListener – Interface for receiving notification events about ServletContext lifecycle changes.
    3. javax.servlet.ServletContextAttributeListener – Interface for receiving notification events about ServletContext attribute changes.
    4. javax.servlet.ServletRequestListener – Interface for receiving notification events about requests coming into and going out of scope of a web application.
    5. javax.servlet.ServletRequestAttributeListener – Interface for receiving notification events about ServletRequest attribute changes.
    6. javax.servlet.http.HttpSessionListener – Interface for receiving notification events about HttpSession lifecycle changes.
    7. javax.servlet.http.HttpSessionBindingListener – Causes an object to be notified when it is bound to or unbound from a session.
    8. javax.servlet.http.HttpSessionAttributeListener – Interface for receiving notification events about HttpSession attribute changes.
    9. javax.servlet.http.HttpSessionActivationListener – Objects that are bound to a session may listen to container events notifying them that sessions will be passivated and that session will be activated. A container that migrates session between VMs or persists sessions is required to notify all attributes bound to sessions implementing HttpSessionActivationListener.

  5. Servlet Listener Configuration

  6. We can use @WebListener annotation to declare a class as Listener, however the class should implement one or more of the Listener interfaces.

    We can define listener in web.xml as:


  7. Servlet Listener Example

  8. Let’s create a simple web application to see servlet listener in action. We will create dynamic web project in Eclipse ServletListenerExample those project structure will look like below image.

    Servlet Listener, Servlet Listener Example, ServletContextListener

    web.xml: In deployment descriptor, I will define some context init params and listener configuration.

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns:xsi="" xmlns="" xsi:schemaLocation="" id="WebApp_ID" version="3.0">

    DBConnectionManager: This is the class for database connectivity, for simplicity I am not providing code for actual database connection. We will set this object as attribute to servlet context.

    package com.journaldev.db;
    import java.sql.Connection;
    public class DBConnectionManager {
    	private String dbURL;
    	private String user;
    	private String password;
    	private Connection con;
    	public DBConnectionManager(String url, String u, String p){
    		//create db connection now
    	public Connection getConnection(){
    		return this.con;
    	public void closeConnection(){
    		//close DB connection here

    MyServlet: A simple servlet class where I will work with session, attributes etc.

    package com.journaldev.servlet;
    import javax.servlet.ServletContext;
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;
    public class MyServlet extends HttpServlet {
    	private static final long serialVersionUID = 1L;
    	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    			ServletContext ctx = request.getServletContext();
    			ctx.setAttribute("User", "Pankaj");
    			String user = (String) ctx.getAttribute("User");
    			HttpSession session = request.getSession();
    			PrintWriter out = response.getWriter();
    			out.write("Hi "+user);

    Now we will implement listener classes, I am providing sample listener classes for commonly used listeners – ServletContextListener, ServletContextAttributeListener, ServletRequestListener and HttpSessionListener.

  9. ServletContextListener

  10. We will read servlet context init parameters to create the DBConnectionManager object and set it as attribute to the ServletContext object.

    package com.journaldev.listener;
    import javax.servlet.ServletContext;
    import javax.servlet.ServletContextEvent;
    import javax.servlet.ServletContextListener;
    import javax.servlet.annotation.WebListener;
    import com.journaldev.db.DBConnectionManager;
    public class AppContextListener implements ServletContextListener {
        public void contextInitialized(ServletContextEvent servletContextEvent) {
        	ServletContext ctx = servletContextEvent.getServletContext();
        	String url = ctx.getInitParameter("DBURL");
        	String u = ctx.getInitParameter("DBUSER");
        	String p = ctx.getInitParameter("DBPWD");
        	//create database connection from init parameters and set it to context
        	DBConnectionManager dbManager = new DBConnectionManager(url, u, p);
        	ctx.setAttribute("DBManager", dbManager);
        	System.out.println("Database connection initialized for Application.");
        public void contextDestroyed(ServletContextEvent servletContextEvent) {
        	ServletContext ctx = servletContextEvent.getServletContext();
        	DBConnectionManager dbManager = (DBConnectionManager) ctx.getAttribute("DBManager");
        	System.out.println("Database connection closed for Application.");

  11. ServletContextAttributeListener

  12. A simple implementation to log the event when attribute is added, removed or replaced in servlet context.

    package com.journaldev.listener;
    import javax.servlet.ServletContextAttributeEvent;
    import javax.servlet.ServletContextAttributeListener;
    import javax.servlet.annotation.WebListener;
    public class AppContextAttributeListener implements ServletContextAttributeListener {
        public void attributeAdded(ServletContextAttributeEvent servletContextAttributeEvent) {
        	System.out.println("ServletContext attribute added::{"+servletContextAttributeEvent.getName()+","+servletContextAttributeEvent.getValue()+"}");
        public void attributeReplaced(ServletContextAttributeEvent servletContextAttributeEvent) {
        	System.out.println("ServletContext attribute replaced::{"+servletContextAttributeEvent.getName()+","+servletContextAttributeEvent.getValue()+"}");
        public void attributeRemoved(ServletContextAttributeEvent servletContextAttributeEvent) {
        	System.out.println("ServletContext attribute removed::{"+servletContextAttributeEvent.getName()+","+servletContextAttributeEvent.getValue()+"}");

  13. HttpSessionListener

  14. A simple implementation to log the event when session is created or destroyed.

    package com.journaldev.listener;
    import javax.servlet.annotation.WebListener;
    import javax.servlet.http.HttpSessionEvent;
    import javax.servlet.http.HttpSessionListener;
    public class MySessionListener implements HttpSessionListener {
        public void sessionCreated(HttpSessionEvent sessionEvent) {
        	System.out.println("Session Created:: ID="+sessionEvent.getSession().getId());
        public void sessionDestroyed(HttpSessionEvent sessionEvent) {
        	System.out.println("Session Destroyed:: ID="+sessionEvent.getSession().getId());

  15. ServletRequestListener

  16. A simple implementation of ServletRequestListener interface to log the ServletRequest IP address when request is initialized and destroyed.

    package com.journaldev.listener;
    import javax.servlet.ServletRequest;
    import javax.servlet.ServletRequestEvent;
    import javax.servlet.ServletRequestListener;
    import javax.servlet.annotation.WebListener;
    public class MyServletRequestListener implements ServletRequestListener {
        public void requestDestroyed(ServletRequestEvent servletRequestEvent) {
        	ServletRequest servletRequest = servletRequestEvent.getServletRequest();
        	System.out.println("ServletRequest destroyed. Remote IP="+servletRequest.getRemoteAddr());
        public void requestInitialized(ServletRequestEvent servletRequestEvent) {
        	ServletRequest servletRequest = servletRequestEvent.getServletRequest();
        	System.out.println("ServletRequest initialized. Remote IP="+servletRequest.getRemoteAddr());

    Now when we will deploy our application and access MyServlet in browser with URL http://localhost:8080/ServletListenerExample/MyServlet, we will see following logs in the server log file.

    ServletContext attribute added::{DBManager,com.journaldev.db.DBConnectionManager@4def3d1b}
    Database connection initialized for Application.
    ServletContext attribute added::{org.apache.jasper.compiler.TldLocationsCache,org.apache.jasper.compiler.TldLocationsCache@1594df96}
    ServletRequest initialized. Remote IP=0:0:0:0:0:0:0:1%0
    ServletContext attribute added::{User,Pankaj}
    ServletContext attribute removed::{User,Pankaj}
    Session Created:: ID=8805E7AE4CCCF98AFD60142A6B300CD6
    Session Destroyed:: ID=8805E7AE4CCCF98AFD60142A6B300CD6
    ServletRequest destroyed. Remote IP=0:0:0:0:0:0:0:1%0
    ServletRequest initialized. Remote IP=0:0:0:0:0:0:0:1%0
    ServletContext attribute added::{User,Pankaj}
    ServletContext attribute removed::{User,Pankaj}
    Session Created:: ID=88A7A1388AB96F611840886012A4475F
    Session Destroyed:: ID=88A7A1388AB96F611840886012A4475F
    ServletRequest destroyed. Remote IP=0:0:0:0:0:0:0:1%0
    Database connection closed for Application.

    Notice the sequence of logs and it’s in the order of execution. The last log will appear when you will shutdown the application or shutdown the container.

Thats all for listener in servlet, we will look into cookies and some common servlet examples next.

You can download the project from below link and play around with it to learn more.

Check out next article in the series about Cookies in Servlet.


  1. Vikas says:

    Extremely useful. Thank you so much,

  2. Gopinath Ghanghao says:

    Thank You very much sir for creating and sharing this wonderful tutorials Keep Making and help others

  3. Anju boura says:

    What is the real or practical use of listeners.

    1. Apurwa Anand says:

      Filters are basically used for logging and auditing purpose before the request reaches the servlet or after the response is generated but before sending it to tge user. Whereas listeners are used to track and log internal object, session, attribute life cycles within a servlet. Hope it helps.

  4. Hemani says:


    I have created an AppContextListener in my class and I have added a line of code as follows in contextInitialized method:
    ValueHandler handler= new ValueHandler ();

    While building, I run mvn clean and mvn install commands. I get build successful message. But when I start my server, I get the following error:

    java.lang.NoClassDefFoundError: com/comp/proj/common/ValueHandler
    at com.comp.proj.context.AppContextListener.contextInitialized(
    at org.apache.catalina.core.StandardContext.listenerStart(
    at org.apache.catalina.core.StandardContext.startInternal(
    at org.apache.catalina.util.LifecycleBase.start(
    at org.apache.catalina.core.ContainerBase$
    at org.apache.catalina.core.ContainerBase$
    at java.util.concurrent.ThreadPoolExecutor.runWorker(
    at java.util.concurrent.ThreadPoolExecutor$

    Please help me with this.

  5. Vikram says:

    Can you please explain why each object has been created twice as in servlet class pankaj has been added and removed only once?

    ServletRequest initialized. Remote IP=0:0:0:0:0:0:0:1%0
    ServletContext attribute added::{User,Pankaj}
    ServletContext attribute removed::{User,Pankaj}
    Session Created:: ID=8805E7AE4CCCF98AFD60142A6B300CD6
    Session Destroyed:: ID=8805E7AE4CCCF98AFD60142A6B300CD6
    ServletRequest destroyed. Remote IP=0:0:0:0:0:0:0:1%0

    ServletRequest initialized. Remote IP=0:0:0:0:0:0:0:1%0
    ServletContext attribute added::{User,Pankaj}
    ServletContext attribute removed::{User,Pankaj}
    Session Created:: ID=88A7A1388AB96F611840886012A4475F
    Session Destroyed:: ID=88A7A1388AB96F611840886012A4475F
    ServletRequest destroyed. Remote IP=0:0:0:0:0:0:0:1%0

  6. Sreejesh says:

    Hi Pankaj

    Nice doubt – will the listener executed in the same thread that handles request? Or is this done in a separate thread?

    1. Eric Pabst says:

      I’m pretty sure it’s in the same thread that handles the request.

  7. matthung says:

    Great tutorial, thanks for sharing!

    1. Pankaj says:

      you are welcome Matt.

  8. nisarg p says:

    one more question earlier versions of servlet listeners are executed the order in which it is defined in web.xml .what about servlet 3.0 because in servlet 3.0 we are using @webListener annotation .pls clarify doubt.

    Thanks Nisarg P

    1. Pankaj says:

      For ordering, you will have to define them in web.xml file. We can’t use annotations to define the order of listener execution.


  9. subba says:

    Nice explanation. East to follow

    1. John says:

      Do you have tutorials for Spring Boot?

      1. Pankaj says:

        I have posted about Spring Boot sometime back, search it and you will find it. 🙂

  10. Petr says:

    ServletContext ctx = request.getServletContext();


    ServletContext ctx = req.getSession().getServletContext();


    1. Pankaj says:

      Both are same. Let’s say you are in a utility class where you have access to only session object, then you can use session class method to get servlet context.

  11. Charmi Chavda says:

    very simply explain and to the point. Thanks for this tutorial 🙂

    1. Pankaj says:

      you are welcome Charmi.

  12. Jbm says:

    I read this and the past four articles you wrote on servlet programming. I am very grateful with you for your will to share your knowledge.

    1. Pankaj says:

      Thanks for liking my work friend.

  13. Saurav Das says:


  14. photon says:

    Thank you so much. All of servlet tutorials are very useful.

    1. Ullu says:

      Tutoirials are very good thanks for the knowledge sharing

  15. Ravi says:

    Nice post. Very helpful in understanding the listener concepts.

  16. Artur says:

    Your tutorials are very helpful and so good described! It is hard to find such good described tutorials. Well done

    1. Pankaj says:

      Thanks Artur for the compliments.

  17. Arpit says:

    Hello Pankaj sir this is arpit i am work on a one small project in this project i have a some of xml file which is in different different folder how we fetch the data from these xml file and save into a database . and how we can recognize this it reads all xml file or it missing any file .

    1. Pankaj says:

      You need to work on Java IO to list files in directory, read files and process them.

  18. Ram says:

    Hi Pankaj

    Thanks a lot for the excellent tutorial.
    I am able to see all the logs except the last one.
    Could you please help me figure out how to check the last log ?
    The article says “The last log will appear when you will shutdown the application or shutdown the container. ” But I am unable to check this.

    Sorry in advance if this is a silly question…..


    1. Pankaj says:

      No question is sill question. You need to either undeploy the application or stop the Tomcat or any other server you might be using to get the last logs.

  19. niraj says:

    i read your materials about servlet-jsp and much more…compare oracle documentation it is very understandable and interesting materials thks mr.pankaj..

    1. Pankaj says:

      you are welcome niraj.

  20. AjiYakin says:

    Great article….

  21. sumit kumar pandey says:

    your explanation is excellent ..

  22. Anshuman Dwivedi says:

    Simple words and easy way to convey complex concepts. Helping and understandable.

  23. Anand says:

    Hi Pankaj,

    I am trying to load a property file in struts2 using ServletContextListener, but I dont know how to access the properties from Business or DAO classes. Please refer the Struts2 doc link –

    Once the context is intialized during the server start-up or application deployment, the properties would be available throughout the application. But, I dont know how to access the properties from the Business or DAO layers. Can you please suggest me something on this?


    1. Pankaj says:

      1. You need to pass session or request objects to the code where you want to read the attributes values.

      2. Best you can do is to create a class with static variables and initialize them. Then you can read it from anywhere without need to pass request or session objects to your business layer.

  24. pzeszko says:

    Thank you very much for this wonderful tutorial. I believe it’s the best available on the Internet, I really like the way you explain stuff : starting with telling why we need something, then giving us complete example with comments. Greetings

    1. Pankaj says:

      Thanks for the nice comment brother, these kind of comments help me keep going.

  25. Akash Deep says:

    Nice article, Thanks !

  26. Suresh says:

    Good Work Pankaj, Simple and Easy to understand..:)

  27. Manish Singh says:

    Hi Pankaj Boss, I too graduated from NIT Jamshedpur. Nice to see you doing such great jobs. It gives us inspiration

    1. Pankaj says:

      Thanks Manish, i hope you liked it. It’s good to see someone from my college to comment.

  28. karan says:

    I have a web application and for that I want to capture the IP address of the clients who are accessing my website and inserting that IP address in oracle database table . so that I can know what region is the most accessing the application. I am using Java EE in my application.

    1. Pankaj says:

      you can use request.getRemoteAddr() method.

  29. amol says:

    How can launch a listener without using the web.xml ?


    1. Pankaj says:

      You can either configure them in the web.xml or use @WebListener annotation.

      1. Gilbert Lopez says:

        I believe another option is to register a listener using one of the addListener methods defined on ServletContext. (Java EE6)

        “In order to receive these notification events, the implementation class must be either declared in the deployment descriptor of the web application, annotated with WebListener, or registered via one of the addListener methods defined on ServletContext.”

        1. Pankaj says:

          Yes, you can do it programmatically too. But web.xml is the preferred way to keep it configurable.

  30. partha says:

    Excellent examples for Listener,helped me a lot in understanding the concept of Listener.Good work,keep it up pankaj.

    1. Pankaj says:

      Thanks for the nice words Partha.

  31. Mitesh Jani says:

    Excellent stuff i understood the concept easily

  32. siva says:

    Awesome man, good job. Keep up the good work. Plz provide sme tutorials on SOAP based web services and Rest full webservices

  33. harry says:

    write a simple programs about HttpSessionActivationListener and HttpSessionBindingListener

  34. kishore krish says:

    really very use full stuff, i enjoyed this. why don’t you publish some articles regarding hibernate

    1. Pankaj says:

      I will be posting about Hibernate in next few months, thats on my TODO list. 🙂

  35. rahul says:

    please explain Servlet context listener in detail

    1. Pankaj says:

      The details of ServletContextListener are already provided with example, let me know what extra details you need.

  36. Siddu says:

    Which design patterns they used to implement listeners internally?

    1. fgty says:

      Its Observer Design Pattern for Servlet Listener

  37. siddu says:

    Servlets Listeners are the example of which design pattern?.
    is HttpServletRequest,ServletContext,HttpSession are thread safe?
    Could you please explain.

  38. HOUSSEM says:

    can you tell me WHY whenever I call the first page index.html in myproject I GOT 104 LINES LIKE THAT:
    .2013-11-27T05:25:54.419+0100|INFO: ServletRequest initialized. Remote IP=
    .2013-11-27T05:25:54.420+0100|INFO: ServletRequest destroyed. Remote IP=
    The MyServletRequestListener is loging for what exactly ?

    An other question please:
    How can I get these output from the servlet to an EJB or a simple managed bean .. I always get errors .
    I am one from the JEE7 newbies.

    And thanks in advance.

    1. Pankaj says:

      There is no way you can get 104 lines for single request.

  39. Devendra says:

    Very nice explanation with example… I was quite not clear even after reading oracle doc . Now got it. Thanks 🙂

  40. Aditya C says:

    Superb Thanks a lot..
    i always love to understand with examples and you explain everything with examples Thanks a lot

  41. Saurabh Gupta says:

    great efforts,

    Can you explain session management for multi-threaded / Concurrency environment. If possible, please demonstrate with example

    1. Pankaj says:

      Servlets are multi-threaded and every request is handled by a separate thread of the servlet. Regarding shared objects across multiple threads of the servlet instance, you need to make sure it’s not causing any side effects.

  42. Matt Felzani says:

    Is there any limitation on the number of each Listener? That is, can I have multiple ServletContextListener instances? And if so, is the processing order guaranteed to be that of how they’re listed in the web.xml file? I would have expected to see a construct similar to the servlet‘s load-on-startup, but it doesn’t appear to be there?

    1. Pankaj says:

      You can have multiple ServletContextListener implementations.

      Implementations of javax.servlet.ServletContextListener are invoked at their contextInitialized method in the order in which they have been declared in web.xml, and at their contextDestroyed method in reverse order.

Leave a Reply

Your email address will not be published. Required fields are marked *

Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages