Listener is one of the most popular technologies used in the J2EE web application. It is part of the Java Servlet as defined in Servlet 2.3 but they have their own specific functionalities. There are two most widely used Servlet Listener i.e. ServletContextListener and HttpSessionListener.

By the end of this tutorial, you are expected to be able to implement ServletContextListener as well as HttpSessionListener and able to customize them based on your needs. Additionally, it would be good if you have some basic knowledge on general J2EE web application such as JSP, Java Servlet and NetBeans.


In this article, we are going to see how to implement the simple ServletContextListener as well as simple HttpSessionListener. Here are the details for this article.

  1. What is Listener?
  2. Creating Project in NetBeans
  3. Implementation of ServletContextListener
  4. Implementation of HttpSessionListener
  5. Conclusion

What is Listener?

Listener is basically pre-defined interfaces that are available for developers in the application lifecycle to achieve some tasks especially when dealing with the ServletContext as well as HttpSession objects. While it saves a lot of time, it also makes the application less complex and more maintainable. In one web application, multiple listeners are allowed so it means that ServletContextListener may co-exist with HttpSessionListener. As you may have known, there are two Listeners that are widely used i.e. ServletContextListener and HttpSessionListener. They both are having different functionalities but both are equally important.

ServletContextListener will be executed once your web application is deployed in your application server (Tomcat or etc). If you have any requirements that need to be executed before the application is started, ServletContextListener is the best place for you. ServletContextListener also detects when your web application is removed. For example, if you replace the WAR file in Tomcat, Tomcat will automatically re-deploy your web application based on the latest WAR. Re-deploying means that Tomcat first removes the web application and then deploy the new web application. In this case, ServletContextListener should be able to notice when the web application is destroyed (removed) as well as when the web application is started (deployed). Just for your information, ServletContextListener is produced for you to deal with the ServletContext. Every web application in J2EE will have one ServletContext associated with it. The details of the ServletContext are not covered in this tutorial.

Unlike ServletContextListener, HttpSessionListener deals with the HttpSession object. HttpSession object are always used in every web application and are very useful in maintaining the data as it is available throughout the lifecycle of the web application until it is invalidated or the user closes the browser. This is the definition of HttpSession taken from the Sun website – "Provides a way to identify a user across more than one page request or visit to a Web site and to store information about that user". The details of the HttpSession object are not covered in this tutorial.

Okay, without any more delay, let's get ready for our tutorial. Start your NetBeans 5.0. After it has been completely started, it should look like below screenshots.

Creating Project in NetBeans

Assuming that you have installed NetBeans 5.5 and having Java Development Kit (jdk) 1.5.

First, we have to create a new Web Application Project for our Listener. This Web Application contains all the JSP pages as well as our Servlet and Listener classes. To create a new Web Application in NetBeans 5.5, you can go to the menu and choose File > New Project. A wizard will instantly be displayed to you and you are required to provide some information to configure your Web Application.


As the wizard is displayed as shown on above illustration, choose Web on the left panel and Web Application on the right panel and click Next button. All the other options are used to develop other kind of projects in NetBeans and irrelevant for our tutorial.


In the next step or the second step of configuring our Web Application, you can provide your Web Application a name. Well, please feel free to name it whatever you want. In this case, to make it self-explanatory, I name our Web Application as ListenerWebApp as shown in the below illustration. In the middle of the wizard, there is an option called Server and it has the value of Bundled (Tomcat 5.5.16). It demonstrates that NetBeans 5.5 will use its bundled Tomcat as the default server. Other configuration should remain the same and press Finish button. You can also press the Next button to go to the last page where you can define the frameworks that you would like to use as shown in below illustration. However, we can skip the last step as we do not use any framework for our Listener. Okay, we have completed our configuration of Web Application and we are ready to implement our first Listener.

After completing the Web Application's configuration, you should have a screen similar as below. It will also create one default JSP file called index.jsp on your Web Pages folder.

Implementation of ServletContextListener

As you may have known, ServletContextListener is useful if you would like to initialize your web application with some values in the beginning of your web application. Okay, without wasting any more time, let's start our first Listener which is ServletContextListener.

To create your Listener, you need to right-click your Source Packages section within your Web Application and choose New > Java Class as shown on below figures. We can simply create it as a simple Java class. Subsequently, we need to customize it to be a Listener. Do not worry; it would not be too hard. Please follow the tutorial and you should see how we convert this simple Java class to Listener.

In this wizard, you may define the package for your Java class. Normally, we use Package to group a few Java files that has the same functionalities. For example, if I have for String manipulation and for encoding, I will locate them under the same package called "com.mycompanyname.util" as they both are actually utility classes. So as this is our first Listener, let's create one package called "com.mycompany.listener". The class name is basically your Listener name. To make it self-explanatory, I name it ServletListener. You can leave other configuration as they are.

Once it is completed, it should look like below.


Now, the most important thing is that we need to make the class "implements" the ServletContextListener. So here is my latest


Now, we have an error in our class. Why? Because once we try to implement the javax.servlet.ServletContextListener interface, we need to define a few implementation methods for it. That's why I mentioned earlier that it is the pre-defined interfaces. This is where our job will be started. You need to add two methods for it.

  1. public void contextInitialized(ServletContextEvent arg0)
  2. public void contextDestroyed(ServletContextEvent arg0)

So here is my latest

 public class ServletListener implements javax.servlet.ServletContextListener {

  public void contextInitialized(ServletContextEvent arg0) {
    System.out.println("Servlet Context is initialized....");

  public void contextDestroyed(ServletContextEvent arg0) {
    System.out.println("Servlet Context is destroyed....");


Okay, logically, if our web application is started, the contextInitialized method is executed. If our web application is removed (perhaps shutting down / redeploying web application in Tomcat), contextDestroyed method is executed.

Now, we need to add one more entry in our web.xml.


One thing you need to know that this listener entry MUST be before the <servlet> entry (if any). So here is my latest web.xml looks like.

After that, we can run the project to test our first Listener which is ServletContextListener.

Below shows the browser that is open automatically by NetBeans.

If you carefully looked at the Tomcat console within NetBeans, you will realize that "Servlet Context is initialized…" is printed out. It means that we have successfully implemented our ServletContextListener. How do we test to destroy the ServletContextListener?

Right click your web project and choose Deploy Project. Deploying the project means that removing the application that is currently loaded and loading the new latest application to the Tomcat. By removing the application, it also means that we are destroying the ServletContext object in which should be detected by our ServletContextListener.

Now, look at the Tomcat console again. Yes, we get the desired results. Below illustrations show what I have in my machine.

Implementation of HttpSessionListener

Okay, now, let's go to HttpSessionListener. HttpSessionListener is mostly used for session management. Unlike ServletContextListener, HttpSessionListener is used to deal with the HttpSession object.

Session is considered created if you assign some attribute to it and similarly, it is considered to be destroyed if you have invalidated it. There is a method that you can call in the Session class to invalidate the session. Have you ever seen a web application that will ask you to re-login if you leave the site untouched for certain periods of times? It checks the time you are not active and will invalidate the session if the inactive time has reached the limit.

Albeit Listener is part of the Servlet, we can create a simple Java class and modify it to be a Listener similar to the ServletContextListener.

Now, we have an error in our class. Why? Because once we try to implement the javax.servlet.HttpSessionListener interface, we need to define a few implementation methods for it. That's why I mentioned earlier that it is the pre-defined interfaces. This is where our job will be started. You need to add two methods for it.

  1. public void sessionCreated(HttpSessionEvent arg0)
  2. public void sessionDestroyed(HttpSessionEvent arg0)

So here is my latest



Okay, if you add one attribute to the session, the session will be created for you and it should print out "Session is created". Once you invalidate the session, the session should be destroyed and "Session is destroyed" will be printed out.

Now, we need to add one more entry in our web.xml.


One thing you need to know that this listener entry MUST be before the <servlet> entry (if any). So here is my latest web.xml looks like. Yes, Listener only needs <listener></listener>

If you follow correctly as our previous Listener, you should have something like below illustrations.

This is the latest web.xml that I had. It shows that I am having two listeners at one time.

Ok, actually we have completed our SessionListener. The only thing is that how to test it. There is one thing you can do. Create one JSP on your web application and we will assign some attributes to the sessions (adding attribute means that we are creating the Session). Create your JSP using the wizard and name it whatever you want. For my case, I would like to name it testSession.jsp.

Ok, now let's add some codes to add attribute to the session. We will achieve it using Scriptlet. Scriptlet is basically Java codes that are embedded in our JSP. It helps us in creating our application dynamic. So please add below codes in your JSP.

		System.out.println("Adding attribute to Session...");
		request.getSession().setAttribute("test", "test");
		System.out.println("Adding attribute to Session completed!");
		System.out.println("Removing Session...");
		System.out.println("Removing Session completed!");		
		out.println("Successfully adding and removing attributes from Session");	

This scriptlet can be placed anywhere in your JSP. For this example, I can just put it within my <body></body> tag. If you are in the right track, it should look like below screenshot.

Create the JSP file by right click your Web Pages and choose New then JSP…

The newly created JSP should look like below illustration.

Add the scriptlet to test our HttpSessionListener.

Now, to try both Listeners, let's deploy our web application again.

Try to execute the testSession.jsp by typing in the URL manually in your browser.

This is the desired output that I grabbed from my local Tomcat console.

 public class SessionListener implements javax.servlet.http.HttpSessionListener {

  public void sessionCreated(HttpSessionEvent arg0) {
    System.out.println("Session is created");

  public void sessionDestroyed(HttpSessionEvent arg0) {
    System.out.println("Session is destroyed");


Well, you should have successfully implemented both ServletContextListener as well as HttpSessionListener. These two listeners are the most widely used and I hope that by reading the tutorial, you have a clear way and objective when you are moving forward with J2EE programming. There are still much to be learnt and please do not worry as this is not hard. My suggestion is to try the sample in this tutorial and try to customize it. Your skills will be much improved by practicing more. There are also two additional Listeners that are not mentioned in this tutorial which are ServletContextAttributeListener and HttpSessionAttributeListener. They are just slightly different with our tutorial. Have a look at them and try them out.

You can find the NetBeans project for the tutorial source codes here.
The README file for the source codes is available here.