Tutorial

ServletContextListener Servlet Listener Example

Published on August 3, 2022
author

Pankaj

ServletContextListener Servlet Listener Example

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

  9. Why do we have Servlet Listener?

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.8. ### Servlet Listener Interfaces and Event Objects

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.

  10. Servlet Listener Configuration

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:

<listener>
    <listener-class>
    com.journaldev.listener.AppContextListener
    </listener-class>
</listener>
  1. Servlet Listener Example

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="https://www.w3.org/2001/XMLSchema-instance" xmlns="https://java.sun.com/xml/ns/javaee" xsi:schemaLocation="https://java.sun.com/xml/ns/javaee https://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>ServletListenerExample</display-name>
  
  <context-param>
    <param-name>DBUSER</param-name>
    <param-value>pankaj</param-value>
  </context-param>
  <context-param>
    <param-name>DBPWD</param-name>
    <param-value>password</param-value>
  </context-param>
  <context-param>
    <param-name>DBURL</param-name>
    <param-value>jdbc:mysql://localhost/mysql_db</param-value>
  </context-param>
  
  <listener>
    <listener-class>com.journaldev.listener.AppContextListener</listener-class>
  </listener>
  <listener>
    <listener-class>com.journaldev.listener.AppContextAttributeListener</listener-class>
  </listener>
  <listener>
    <listener-class>com.journaldev.listener.MySessionListener</listener-class>
  </listener>
  <listener>
    <listener-class>com.journaldev.listener.MyServletRequestListener</listener-class>
  </listener>
</web-app>

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){
		this.dbURL=url;
		this.user=u;
		this.password=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 java.io.IOException;
import java.io.PrintWriter;

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;

@WebServlet("/MyServlet")
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");
			ctx.removeAttribute("User");
			
			HttpSession session = request.getSession();
			session.invalidate();
			
			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.27. ## ServletContextListener

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;

@WebListener
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");
    	dbManager.closeConnection();
    	System.out.println("Database connection closed for Application.");
    	
    }
	
}
  1. ServletContextAttributeListener

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;

@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()+"}");
    }
	
}
  1. HttpSessionListener

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;

@WebListener
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());
    }
	
}
  1. ServletRequestListener

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;

@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 https://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.

Download Servlet Listener Example Project

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

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the author(s)

Category:
Tutorial

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
October 11, 2013

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?

- Matt Felzani

JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
June 10, 2016

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.

- Pankaj

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    October 17, 2013

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

    - Saurabh Gupta

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    October 17, 2013

    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.

    - Pankaj

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      November 3, 2013

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

      - Aditya C

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        November 13, 2013

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

        - Devendra

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          November 27, 2013

          Hi, 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=127.0.0.1 .2013-11-27T05:25:54.420+0100|INFO: ServletRequest destroyed. Remote IP=127.0.0.1 . . . . . 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.

          - HOUSSEM

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          November 27, 2013

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

          - Pankaj

            JournalDev
            DigitalOcean Employee
            DigitalOcean Employee badge
            December 9, 2013

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

            - siddu

              JournalDev
              DigitalOcean Employee
              DigitalOcean Employee badge
              January 24, 2014

              Which design patterns they used to implement listeners internally?

              - Siddu

              JournalDev
              DigitalOcean Employee
              DigitalOcean Employee badge
              July 29, 2014

              Its Observer Design Pattern for Servlet Listener

              - fgty

                JournalDev
                DigitalOcean Employee
                DigitalOcean Employee badge
                January 27, 2014

                please explain Servlet context listener in detail

                - rahul

                JournalDev
                DigitalOcean Employee
                DigitalOcean Employee badge
                January 27, 2014

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

                - Pankaj

                  JournalDev
                  DigitalOcean Employee
                  DigitalOcean Employee badge
                  March 4, 2014

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

                  - kishore krish

                  JournalDev
                  DigitalOcean Employee
                  DigitalOcean Employee badge
                  March 4, 2014

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

                  - Pankaj

                    JournalDev
                    DigitalOcean Employee
                    DigitalOcean Employee badge
                    March 21, 2014

                    write a simple programs about HttpSessionActivationListener and HttpSessionBindingListener

                    - harry

                      JournalDev
                      DigitalOcean Employee
                      DigitalOcean Employee badge
                      April 14, 2014

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

                      - siva

                        JournalDev
                        DigitalOcean Employee
                        DigitalOcean Employee badge
                        April 27, 2014

                        Excellent stuff i understood the concept easily

                        - Mitesh Jani

                          JournalDev
                          DigitalOcean Employee
                          DigitalOcean Employee badge
                          May 23, 2014

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

                          - partha

                          JournalDev
                          DigitalOcean Employee
                          DigitalOcean Employee badge
                          June 10, 2016

                          Thanks for the nice words Partha.

                          - Pankaj

                            JournalDev
                            DigitalOcean Employee
                            DigitalOcean Employee badge
                            May 30, 2014

                            Hi, How can launch a listener without using the web.xml ? Regards, Amol

                            - amol

                            JournalDev
                            DigitalOcean Employee
                            DigitalOcean Employee badge
                            May 30, 2014

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

                            - Pankaj

                            JournalDev
                            DigitalOcean Employee
                            DigitalOcean Employee badge
                            November 10, 2014

                            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.”

                            - Gilbert Lopez

                            JournalDev
                            DigitalOcean Employee
                            DigitalOcean Employee badge
                            June 10, 2016

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

                            - Pankaj

                              JournalDev
                              DigitalOcean Employee
                              DigitalOcean Employee badge
                              June 3, 2014

                              sir, 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.

                              - karan

                              JournalDev
                              DigitalOcean Employee
                              DigitalOcean Employee badge
                              June 10, 2016

                              you can use request.getRemoteAddr() method.

                              - Pankaj

                                JournalDev
                                DigitalOcean Employee
                                DigitalOcean Employee badge
                                June 9, 2014

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

                                - Manish Singh

                                JournalDev
                                DigitalOcean Employee
                                DigitalOcean Employee badge
                                June 9, 2014

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

                                - Pankaj

                                  JournalDev
                                  DigitalOcean Employee
                                  DigitalOcean Employee badge
                                  June 19, 2014

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

                                  - Suresh

                                    JournalDev
                                    DigitalOcean Employee
                                    DigitalOcean Employee badge
                                    July 1, 2014

                                    Nice article, Thanks !

                                    - Akash Deep

                                      JournalDev
                                      DigitalOcean Employee
                                      DigitalOcean Employee badge
                                      August 27, 2014

                                      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

                                      - pzeszko

                                      JournalDev
                                      DigitalOcean Employee
                                      DigitalOcean Employee badge
                                      June 10, 2016

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

                                      - Pankaj

                                        JournalDev
                                        DigitalOcean Employee
                                        DigitalOcean Employee badge
                                        September 22, 2014

                                        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 - https://struts.apache.org/release/2.3.x/docs/how-do-i-set-a-global-resource-bundle.html 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? Thanks, Anand…

                                        - Anand

                                        JournalDev
                                        DigitalOcean Employee
                                        DigitalOcean Employee badge
                                        June 10, 2016

                                        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.

                                        - Pankaj

                                          JournalDev
                                          DigitalOcean Employee
                                          DigitalOcean Employee badge
                                          October 11, 2014

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

                                          - Anshuman Dwivedi

                                            JournalDev
                                            DigitalOcean Employee
                                            DigitalOcean Employee badge
                                            October 21, 2014

                                            your explanation is excellent …

                                            - sumit kumar pandey

                                              JournalDev
                                              DigitalOcean Employee
                                              DigitalOcean Employee badge
                                              November 13, 2014

                                              thanks a lot!

                                              - popping57

                                                JournalDev
                                                DigitalOcean Employee
                                                DigitalOcean Employee badge
                                                November 15, 2014

                                                Great article…

                                                - AjiYakin

                                                  JournalDev
                                                  DigitalOcean Employee
                                                  DigitalOcean Employee badge
                                                  November 24, 2014

                                                  Nice article, thanks!

                                                  - Robert Rusu

                                                    JournalDev
                                                    DigitalOcean Employee
                                                    DigitalOcean Employee badge
                                                    December 10, 2014

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

                                                    - niraj

                                                    JournalDev
                                                    DigitalOcean Employee
                                                    DigitalOcean Employee badge
                                                    June 10, 2016

                                                    you are welcome niraj.

                                                    - Pankaj

                                                      JournalDev
                                                      DigitalOcean Employee
                                                      DigitalOcean Employee badge
                                                      January 7, 2015

                                                      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… Regards Ram

                                                      - Ram

                                                      JournalDev
                                                      DigitalOcean Employee
                                                      DigitalOcean Employee badge
                                                      January 7, 2015

                                                      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.

                                                      - Pankaj

                                                        JournalDev
                                                        DigitalOcean Employee
                                                        DigitalOcean Employee badge
                                                        January 30, 2015

                                                        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 .

                                                        - Arpit

                                                        JournalDev
                                                        DigitalOcean Employee
                                                        DigitalOcean Employee badge
                                                        June 10, 2016

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

                                                        - Pankaj

                                                          JournalDev
                                                          DigitalOcean Employee
                                                          DigitalOcean Employee badge
                                                          March 1, 2015

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

                                                          - Artur

                                                          JournalDev
                                                          DigitalOcean Employee
                                                          DigitalOcean Employee badge
                                                          June 10, 2016

                                                          Thanks Artur for the compliments.

                                                          - Pankaj

                                                            JournalDev
                                                            DigitalOcean Employee
                                                            DigitalOcean Employee badge
                                                            March 11, 2015

                                                            Nice post. Very helpful in understanding the listener concepts.

                                                            - Ravi

                                                              JournalDev
                                                              DigitalOcean Employee
                                                              DigitalOcean Employee badge
                                                              April 6, 2015

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

                                                              - photon

                                                              JournalDev
                                                              DigitalOcean Employee
                                                              DigitalOcean Employee badge
                                                              May 12, 2015

                                                              Tutoirials are very good thanks for the knowledge sharing

                                                              - Ullu

                                                              JournalDev
                                                              DigitalOcean Employee
                                                              DigitalOcean Employee badge
                                                              June 10, 2016

                                                              Thanks friends.

                                                              - Pankaj

                                                                JournalDev
                                                                DigitalOcean Employee
                                                                DigitalOcean Employee badge
                                                                July 4, 2015

                                                                Thanks

                                                                - Saurav Das

                                                                  JournalDev
                                                                  DigitalOcean Employee
                                                                  DigitalOcean Employee badge
                                                                  December 22, 2015

                                                                  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.

                                                                  - Jbm

                                                                  JournalDev
                                                                  DigitalOcean Employee
                                                                  DigitalOcean Employee badge
                                                                  June 10, 2016

                                                                  Thanks for liking my work friend.

                                                                  - Pankaj

                                                                    JournalDev
                                                                    DigitalOcean Employee
                                                                    DigitalOcean Employee badge
                                                                    January 22, 2016

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

                                                                    - Charmi Chavda

                                                                    JournalDev
                                                                    DigitalOcean Employee
                                                                    DigitalOcean Employee badge
                                                                    June 10, 2016

                                                                    you are welcome Charmi.

                                                                    - Pankaj

                                                                      JournalDev
                                                                      DigitalOcean Employee
                                                                      DigitalOcean Employee badge
                                                                      February 4, 2016

                                                                      ServletContext ctx = request.getServletContext(); or ServletContext ctx = req.getSession().getServletContext(); ???

                                                                      - Petr

                                                                      JournalDev
                                                                      DigitalOcean Employee
                                                                      DigitalOcean Employee badge
                                                                      June 10, 2016

                                                                      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.

                                                                      - Pankaj

                                                                        JournalDev
                                                                        DigitalOcean Employee
                                                                        DigitalOcean Employee badge
                                                                        March 3, 2016

                                                                        Nice explanation. East to follow

                                                                        - subba

                                                                        JournalDev
                                                                        DigitalOcean Employee
                                                                        DigitalOcean Employee badge
                                                                        April 30, 2016

                                                                        Do you have tutorials for Spring Boot?

                                                                        - John

                                                                        JournalDev
                                                                        DigitalOcean Employee
                                                                        DigitalOcean Employee badge
                                                                        June 10, 2016

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

                                                                        - Pankaj

                                                                          JournalDev
                                                                          DigitalOcean Employee
                                                                          DigitalOcean Employee badge
                                                                          May 31, 2016

                                                                          one more question pankaj.in 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

                                                                          - nisarg p

                                                                          JournalDev
                                                                          DigitalOcean Employee
                                                                          DigitalOcean Employee badge
                                                                          June 10, 2016

                                                                          For ordering, you will have to define them in web.xml file. We can’t use annotations to define the order of listener execution. Ref: https://stackoverflow.com/questions/19729370/servletcontextlistener-execution-order

                                                                          - Pankaj

                                                                            JournalDev
                                                                            DigitalOcean Employee
                                                                            DigitalOcean Employee badge
                                                                            June 7, 2016

                                                                            Great tutorial, thanks for sharing!

                                                                            - matthung

                                                                            JournalDev
                                                                            DigitalOcean Employee
                                                                            DigitalOcean Employee badge
                                                                            June 10, 2016

                                                                            you are welcome Matt.

                                                                            - Pankaj

                                                                              JournalDev
                                                                              DigitalOcean Employee
                                                                              DigitalOcean Employee badge
                                                                              July 13, 2016

                                                                              Hi Pankaj Nice article…one doubt - will the listener executed in the same thread that handles request? Or is this done in a separate thread?

                                                                              - Sreejesh

                                                                              JournalDev
                                                                              DigitalOcean Employee
                                                                              DigitalOcean Employee badge
                                                                              December 9, 2016

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

                                                                              - Eric Pabst

                                                                                JournalDev
                                                                                DigitalOcean Employee
                                                                                DigitalOcean Employee badge
                                                                                January 23, 2017

                                                                                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

                                                                                - Vikram

                                                                                  JournalDev
                                                                                  DigitalOcean Employee
                                                                                  DigitalOcean Employee badge
                                                                                  December 21, 2017

                                                                                  Hi 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(AppContextListener.java:35) at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4939) at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5434) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549) at java.util.concurrent.FutureTask.run(FutureTask.java:262) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) at java.lang.Thread.run(Thread.java:744) Please help me with this.

                                                                                  - Hemani

                                                                                    JournalDev
                                                                                    DigitalOcean Employee
                                                                                    DigitalOcean Employee badge
                                                                                    June 25, 2018

                                                                                    What is the real or practical use of listeners.

                                                                                    - Anju boura

                                                                                    JournalDev
                                                                                    DigitalOcean Employee
                                                                                    DigitalOcean Employee badge
                                                                                    July 25, 2018

                                                                                    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.

                                                                                    - Apurwa Anand

                                                                                      JournalDev
                                                                                      DigitalOcean Employee
                                                                                      DigitalOcean Employee badge
                                                                                      September 10, 2018

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

                                                                                      - Gopinath Ghanghao

                                                                                        JournalDev
                                                                                        DigitalOcean Employee
                                                                                        DigitalOcean Employee badge
                                                                                        September 20, 2018

                                                                                        Extremely useful. Thank you so much,

                                                                                        - Vikas

                                                                                          JournalDev
                                                                                          DigitalOcean Employee
                                                                                          DigitalOcean Employee badge
                                                                                          January 28, 2020

                                                                                          Console for the same are as : Jan 28, 2020 3:46:42 PM org.apache.catalina.startup.VersionLoggerListener log INFO: Server version name: Apache Tomcat/9.0.30 Jan 28, 2020 3:46:42 PM org.apache.catalina.startup.VersionLoggerListener log INFO: Server built: Dec 7 2019 16:42:04 UTC Jan 28, 2020 3:46:42 PM org.apache.catalina.startup.VersionLoggerListener log INFO: Server version number: 9.0.30.0 Jan 28, 2020 3:46:42 PM org.apache.catalina.startup.VersionLoggerListener log INFO: OS Name: Windows 10 Jan 28, 2020 3:46:42 PM org.apache.catalina.startup.VersionLoggerListener log INFO: OS Version: 10.0 Jan 28, 2020 3:46:42 PM org.apache.catalina.startup.VersionLoggerListener log INFO: Architecture: amd64 Jan 28, 2020 3:46:42 PM org.apache.catalina.startup.VersionLoggerListener log INFO: Java Home: C:\Program Files\Java\jre1.8.0_144 Jan 28, 2020 3:46:42 PM org.apache.catalina.startup.VersionLoggerListener log INFO: JVM Version: 1.8.0_144-b01 Jan 28, 2020 3:46:42 PM org.apache.catalina.startup.VersionLoggerListener log INFO: JVM Vendor: Oracle Corporation Jan 28, 2020 3:46:42 PM org.apache.catalina.startup.VersionLoggerListener log INFO: CATALINA_BASE: D:\workspace_adp_23Jan\.metadata\.plugins\org.eclipse.wst.server.core\tmp1 Jan 28, 2020 3:46:42 PM org.apache.catalina.startup.VersionLoggerListener log INFO: CATALINA_HOME: D:\Softwares\apache-tomcat-9.0.30 Jan 28, 2020 3:46:42 PM org.apache.catalina.startup.VersionLoggerListener log INFO: Command line argument: -Dcatalina.base=D:\workspace_adp_23Jan\.metadata\.plugins\org.eclipse.wst.server.core\tmp1 Jan 28, 2020 3:46:42 PM org.apache.catalina.startup.VersionLoggerListener log INFO: Command line argument: -Dcatalina.home=D:\Softwares\apache-tomcat-9.0.30 Jan 28, 2020 3:46:42 PM org.apache.catalina.startup.VersionLoggerListener log INFO: Command line argument: -Dwtp.deploy=D:\workspace_adp_23Jan\.metadata\.plugins\org.eclipse.wst.server.core\tmp1\wtpwebapps Jan 28, 2020 3:46:42 PM org.apache.catalina.startup.VersionLoggerListener log INFO: Command line argument: -Djava.endorsed.dirs=D:\Softwares\apache-tomcat-9.0.30\endorsed Jan 28, 2020 3:46:42 PM org.apache.catalina.startup.VersionLoggerListener log INFO: Command line argument: -Dfile.encoding=Cp1252 Jan 28, 2020 3:46:42 PM org.apache.catalina.core.AprLifecycleListener lifecycleEvent INFO: Loaded APR based Apache Tomcat Native library [1.2.23] using APR version [1.7.0]. Jan 28, 2020 3:46:42 PM org.apache.catalina.core.AprLifecycleListener lifecycleEvent INFO: APR capabilities: IPv6 [true], sendfile [true], accept filters [false], random [true]. Jan 28, 2020 3:46:42 PM org.apache.catalina.core.AprLifecycleListener lifecycleEvent INFO: APR/OpenSSL configuration: useAprConnector [false], useOpenSSL [true] Jan 28, 2020 3:46:42 PM org.apache.catalina.core.AprLifecycleListener initializeSSL INFO: OpenSSL successfully initialized [OpenSSL 1.1.1c 28 May 2019] Jan 28, 2020 3:46:43 PM org.apache.coyote.AbstractProtocol init INFO: Initializing ProtocolHandler [“http-nio-8080”] Jan 28, 2020 3:46:43 PM org.apache.coyote.AbstractProtocol init INFO: Initializing ProtocolHandler [“ajp-nio-8009”] Jan 28, 2020 3:46:43 PM org.apache.catalina.startup.Catalina load INFO: Server initialization in [1,509] milliseconds Jan 28, 2020 3:46:43 PM org.apache.catalina.core.StandardService startInternal INFO: Starting service [Catalina] Jan 28, 2020 3:46:43 PM org.apache.catalina.core.StandardEngine startInternal INFO: Starting Servlet engine: [Apache Tomcat/9.0.30] Jan 28, 2020 3:46:48 PM org.apache.jasper.servlet.TldScanner scanJars INFO: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time. Jan 28, 2020 3:46:52 PM org.apache.jasper.servlet.TldScanner scanJars INFO: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time. ServletContext attribute added::{DBManager,com.journaldev.db.DBConnectionManager@78698291} Database connection initialized for Application. Jan 28, 2020 3:46:52 PM org.apache.coyote.AbstractProtocol start INFO: Starting ProtocolHandler [“http-nio-8080”] Jan 28, 2020 3:46:52 PM org.apache.coyote.AbstractProtocol start INFO: Starting ProtocolHandler [“ajp-nio-8009”] Jan 28, 2020 3:46:52 PM org.apache.catalina.startup.Catalina start INFO: Server startup in [9,494] milliseconds ServletRequest initialized. Remote IP=127.0.0.1 ServletRequest destroyed. Remote IP=127.0.0.1

                                                                                          - shweta

                                                                                            JournalDev
                                                                                            DigitalOcean Employee
                                                                                            DigitalOcean Employee badge
                                                                                            January 28, 2020

                                                                                            I downloaded and imported this project but when I am trying to run it on server only DBManager is invoked but the other servlet are not . please clarify whats missing here. Console logs are as : Jan 28, 2020 3:46:42 PM org.apache.catalina.startup.VersionLoggerListener log INFO: Server version name: Apache Tomcat/9.0.30 Jan 28, 2020 3:46:42 PM org.apache.catalina.startup.VersionLoggerListener log INFO: Server built: Dec 7 2019 16:42:04 UTC Jan 28, 2020 3:46:42 PM org.apache.catalina.startup.VersionLoggerListener log INFO: Server version number: 9.0.30.0 Jan 28, 2020 3:46:42 PM org.apache.catalina.startup.VersionLoggerListener log INFO: OS Name: Windows 10 Jan 28, 2020 3:46:42 PM org.apache.catalina.startup.VersionLoggerListener log INFO: OS Version: 10.0 Jan 28, 2020 3:46:42 PM org.apache.catalina.startup.VersionLoggerListener log INFO: Architecture: amd64 Jan 28, 2020 3:46:42 PM org.apache.catalina.startup.VersionLoggerListener log INFO: Java Home: C:\Program Files\Java\jre1.8.0_144 Jan 28, 2020 3:46:42 PM org.apache.catalina.startup.VersionLoggerListener log INFO: JVM Version: 1.8.0_144-b01 Jan 28, 2020 3:46:42 PM org.apache.catalina.startup.VersionLoggerListener log INFO: JVM Vendor: Oracle Corporation Jan 28, 2020 3:46:42 PM org.apache.catalina.startup.VersionLoggerListener log INFO: CATALINA_BASE: D:\workspace_adp_23Jan\.metadata\.plugins\org.eclipse.wst.server.core\tmp1 Jan 28, 2020 3:46:42 PM org.apache.catalina.startup.VersionLoggerListener log INFO: CATALINA_HOME: D:\Softwares\apache-tomcat-9.0.30 Jan 28, 2020 3:46:42 PM org.apache.catalina.startup.VersionLoggerListener log INFO: Command line argument: -Dcatalina.base=D:\workspace_adp_23Jan\.metadata\.plugins\org.eclipse.wst.server.core\tmp1 Jan 28, 2020 3:46:42 PM org.apache.catalina.startup.VersionLoggerListener log INFO: Command line argument: -Dcatalina.home=D:\Softwares\apache-tomcat-9.0.30 Jan 28, 2020 3:46:42 PM org.apache.catalina.startup.VersionLoggerListener log INFO: Command line argument: -Dwtp.deploy=D:\workspace_adp_23Jan\.metadata\.plugins\org.eclipse.wst.server.core\tmp1\wtpwebapps Jan 28, 2020 3:46:42 PM org.apache.catalina.startup.VersionLoggerListener log INFO: Command line argument: -Djava.endorsed.dirs=D:\Softwares\apache-tomcat-9.0.30\endorsed Jan 28, 2020 3:46:42 PM org.apache.catalina.startup.VersionLoggerListener log INFO: Command line argument: -Dfile.encoding=Cp1252 Jan 28, 2020 3:46:42 PM org.apache.catalina.core.AprLifecycleListener lifecycleEvent INFO: Loaded APR based Apache Tomcat Native library [1.2.23] using APR version [1.7.0]. Jan 28, 2020 3:46:42 PM org.apache.catalina.core.AprLifecycleListener lifecycleEvent INFO: APR capabilities: IPv6 [true], sendfile [true], accept filters [false], random [true]. Jan 28, 2020 3:46:42 PM org.apache.catalina.core.AprLifecycleListener lifecycleEvent INFO: APR/OpenSSL configuration: useAprConnector [false], useOpenSSL [true] Jan 28, 2020 3:46:42 PM org.apache.catalina.core.AprLifecycleListener initializeSSL INFO: OpenSSL successfully initialized [OpenSSL 1.1.1c 28 May 2019] Jan 28, 2020 3:46:43 PM org.apache.coyote.AbstractProtocol init INFO: Initializing ProtocolHandler [“http-nio-8080”] Jan 28, 2020 3:46:43 PM org.apache.coyote.AbstractProtocol init INFO: Initializing ProtocolHandler [“ajp-nio-8009”] Jan 28, 2020 3:46:43 PM org.apache.catalina.startup.Catalina load INFO: Server initialization in [1,509] milliseconds Jan 28, 2020 3:46:43 PM org.apache.catalina.core.StandardService startInternal INFO: Starting service [Catalina] Jan 28, 2020 3:46:43 PM org.apache.catalina.core.StandardEngine startInternal INFO: Starting Servlet engine: [Apache Tomcat/9.0.30] Jan 28, 2020 3:46:48 PM org.apache.jasper.servlet.TldScanner scanJars INFO: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time. Jan 28, 2020 3:46:52 PM org.apache.jasper.servlet.TldScanner scanJars INFO: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time. ServletContext attribute added::{DBManager,com.journaldev.db.DBConnectionManager@78698291} Database connection initialized for Application. Jan 28, 2020 3:46:52 PM org.apache.coyote.AbstractProtocol start INFO: Starting ProtocolHandler [“http-nio-8080”] Jan 28, 2020 3:46:52 PM org.apache.coyote.AbstractProtocol start INFO: Starting ProtocolHandler [“ajp-nio-8009”] Jan 28, 2020 3:46:52 PM org.apache.catalina.startup.Catalina start INFO: Server startup in [9,494] milliseconds ServletRequest initialized. Remote IP=127.0.0.1 ServletRequest destroyed. Remote IP=127.0.0.1

                                                                                            - shweta

                                                                                              JournalDev
                                                                                              DigitalOcean Employee
                                                                                              DigitalOcean Employee badge
                                                                                              September 1, 2020

                                                                                              Hi Can we set the value in web.xml file.

                                                                                              - Shyam

                                                                                                JournalDev
                                                                                                DigitalOcean Employee
                                                                                                DigitalOcean Employee badge
                                                                                                October 6, 2021

                                                                                                Can we create our own by extending EventObject and process that with our own listeners.

                                                                                                - dabbara venkatesh

                                                                                                  Try DigitalOcean for free

                                                                                                  Click below to sign up and get $200 of credit to try our products over 60 days!

                                                                                                  Sign up

                                                                                                  Join the Tech Talk
                                                                                                  Success! Thank you! Please check your email for further details.

                                                                                                  Please complete your information!

                                                                                                  Become a contributor for community

                                                                                                  Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

                                                                                                  DigitalOcean Documentation

                                                                                                  Full documentation for every DigitalOcean product.

                                                                                                  Resources for startups and SMBs

                                                                                                  The Wave has everything you need to know about building a business, from raising funding to marketing your product.

                                                                                                  Get our newsletter

                                                                                                  Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

                                                                                                  New accounts only. By submitting your email you agree to our Privacy Policy

                                                                                                  The developer cloud

                                                                                                  Scale up as you grow — whether you're running one virtual machine or ten thousand.

                                                                                                  Get started for free

                                                                                                  Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

                                                                                                  *This promotional offer applies to new accounts only.