Introduction

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

Roadmap

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

So let's start our Eclipse. If you are not sure on how to setup Eclipse and Tomcat, please have a look at the previous tutorials (Java Servlet tutorial).

Creating Project in Eclipse

Assuming that you have installed Eclipse with Web Tools Platform (WTP) Plugin and having Java Development Kit (jdk) 1.5 as well as Tomcat Server 5.5, let's start to create our first Listener. Start Eclipse and you should see similar to below illustration in your screen. Yes, this is the main page of Eclipse.

Image

To create our Listener, we are required to create a Project called Dynamic Web Project. Actually, in the real world application, this Web Project should contain many things such as Servlet, Listener, Filter, JSP, jar files and etc. Well, back to our tutorial, go to your menu, and choose New then Project. A wizard will be prompted to you.

Image

Go to the Web and choose Dynamic Web Project and press Next. If you do not have Dynamic Web Project available, it means that Web Tools Platform (WTP) plugin is not correctly installed. Please re-download it or look at the documentation of Web Tools Platform (WTP) plugin for more details. You may also create your web project manually using the Java Project in Eclipse but it would be more complex and complicated.

Image

A wizard will be displayed to you. The wizard is mainly used to configure our Dynamic Web Project. You are allowed to name your Dynamic Web Project with any name that you wish but please consider to choose the name that is self-explanatory.

For our tutorial's sample, I am going to name my Dynamic Web Project as ListenerWebApp. There is an interesting point worth to be looked at in this wizard. You need to provide the Target Runtime. What does it mean? Well, it basically requests you to identify the server that you would like to use for this Dynamic Web Project; in this case, Apache Tomcat. You may try to click on the combo box to observe whether you have any existing server(s) or not. If not, you may need to create one server for your project. For this tutorial, as you should have read the previous tutorials about Java Servlet, I am going to show you that we are not going to define any server as we are going to start and shutdown Tomcat manually. Starting and shutting down Tomcat manually has few advantages as we are not dependent on the IDE.

Your screen should look like below. Do not enter anything in the Target runtime and press next button.

Image

Next wizard is shown. We can ignore them and keep them as default. Press Next button. For your information, in this wizard, Eclipse is telling you that our web application is using Servlet 2.4 version as well as using Java 5.0. If you carefully read the tutorial, I mentioned that the Listener is available for Servlet 2.3 and above so if you see the version of your Servlet in your Eclipse is less than 2.3, you may have some problems in this tutorial. In short word, you are not using the latest technology.

Image

Now, we are in the last step of our Dynamic Web Project configuration. For this wizard, you should not modify the Context Root albeit you are allowed to do so as to understand the concept of context root may be puzzling. You can leave them as default and when you are more familiar with J2EE area, you may try to play around with it.

Image

You can amend the Content Directory with any name that you wish. Normally, J2EE Developers will name it the same as the Project Name to increase the maintainability of the project. For this tutorial, we are not going to change it and we are going to keep it as default - WebContent. For your information, this directory is the place where all the deployment descriptor, JSP files, other configuration files are located. Press Finish button and we have completed our Dynamic Web Project configuration.

You should be able to see something like below illustration. Yeah, in below illustrations, I have around 7 web applications in my Eclipse.

Image

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.

Right click on the src folder (this is your source folder) and choose New and Class. Although Listener is part of Servlet, 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.

Image

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 StringUtil.java for String manipulation and EncodingAlgorithmUtil.java 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.

Image

Once it is completed, it should look like below.

Image

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

Image

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 ServletListener.java

 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.

<listener>
	<listener-class>com.mycompany.listener.ServletListener</listener-class>
    </listener>  

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.

Image

If you have completed everything, simply export your project into WAR file and deploy it to Tomcat and see what's happening in Tomcat console.

Image

Okay, by this, it means that you have successfully created the ServletContextListener. You can do whatever you want when your web application is started. Normally, this is useful if you are scheduling something then you need to initialize it here.

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.

You can right click on the src folder (this is your source folder) and choose New and Class. Although Listener is part of Servlet, 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.

Image

Once it is completed, it should look like below.

Image

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

Image

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 SessionListener.java

 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");
  }
}

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.

<listener>
	<listener-class>com.mycompany.listener.SessionListener</listener-class>
    </listener>  

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>

So this is how my latest web.xml looks like after implementing both ServletContextListener and HttpSessionListener.

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" 
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
 xsi:schemaLocation=
   "http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

	<display-name>
		ListenerWebApp
	</display-name>
	
    <listener>
		<listener-class>com.mycompany.listener.ServletListener</listener-class>
    </listener>  
	
    <listener>
		<listener-class>com.mycompany.listener.SessionListener</listener-class>
    </listener>  
	
	<welcome-file-list>
		<welcome-file>index.html</welcome-file>
		<welcome-file>index.htm</welcome-file>
		<welcome-file>index.jsp</welcome-file>
		<welcome-file>default.html</welcome-file>
		<welcome-file>default.htm</welcome-file>
		<welcome-file>default.jsp</welcome-file>
	</welcome-file-list>
</web-app>

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...");
	request.getSession().invalidate();
	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.

Image

Let's test it. Export your project into WAR files and deploy it to Tomcat. Access the testSession.jsp that we just created and carefully look at the Tomcat console.

As expected, when the first time Tomcat is loaded, our ServletContextListener is still executed.

Image

Now, open your browser and let's try to execute the testSession.jsp by typing the URL manually into your browser. In my case, it should be http://localhost:8080/ListenerWebApp/testSession.jsp.


This is my Tomcat console now.

Image

Conclusion

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 Eclipse project for the tutorial source codes here.
The README file for the sources is available here.