Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Working with Servlet Context Listeners in Java

In this article we will talk about the servlet context listeners. Servlet context listener is an interface which receives notification events about the serlvet context lifecycle changes.

Servlet Context listeners are also used to initialize database connections, logging and other resources which are used in the application.

A servlet context is created while we deploy the web application. Once a servlet context is created it will be used by all other servlets and jsps. Servlet context is also known as the application scope in web applications.

Defining a servlet context listener:

The listener class must implement the ServletContextListener interface and should provide implmentation for contextIntialized() and contextDestroyed() methods. Let us consider the following code snippet:

Listing 1: Sample code for Hibernate context listener class implementing ServletContextListener interface

package com.home.servletlisteners;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import com.home.hibernate.HibernateUtil;

public class HibernateContextListener implements ServletContextListener{

    public void contextInitialized(ServletContextEvent sce) {
       HibernateUtil.initSessionFactory();
       System.out.println("HIBERNATE SESSION FACTORY INITIALIZED");
    }

    public void contextDestroyed(ServletContextEvent sce) {
	if (HibernateUtil.getSessionFactory()!=null) {
             HibernateUtil.getSessionFactory().close();
        	}
        System.out.println("HIBERNATE SESSION FACTORY DESTROYED");
    }
}
						

The above java code is implementing the servlet context listener interface. This class calls the initiatilizeSessionFactory method of Hibernate util class. This is a sample application code which requires hibernate session to be available for the entire span of the application. Just like any other resource the application requires hibernate session to be active till the application server is turned off. When the application server is turned off we should ensure that the resources which were created at the time of startup should be released. To enable this we use the contextDestroyed method and release the resources which were created in the contextInitialized method.

The hibernate util class which intializes the session factory could be as under:

Listing 2: Hibernate Util class

package com.home.hibernate;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {

	private static SessionFactory sessionFactory;

	/**
	 * Initializes the Hibernate SessionFactory.
	 */
	public static synchronized void initSessionFactory() {
		if (getSessionFactory() != null) {
			throw new IllegalStateException(
					"Hibernate SessionFactory is already initialized");
		}
		try {
			// Create the SessionFactory from the hibernate.cfg.xml
			sessionFactory = new Configuration().configure().buildSessionFactory();
		} catch (Exception e) {
			throw new ExceptionInInitializerError(e);
		}
	}

	public static synchronized SessionFactory getSessionFactory() {
		
		try {
			sessionFactory = new Configuration().configure()
					.buildSessionFactory();
		} catch (Throwable ex) {
			System.err.println("Failed to create sessionFactory object." + ex);
			throw new ExceptionInInitializerError(ex);
		}
		return sessionFactory;
	}
}
 

Servlet context listeners are also used to set context attributes which are used later in the application. The following code snippet is an example which is setting some parameters in the context to be used by the application:

Listing 3: Sample attribute setting in the context

package com.home.servletlisteners;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class SampleServletContextListener implements ServletContextListener {

	public void contextInitialized(ServletContextEvent sce) {
		sce.getServletContext().setAttribute("DEFAULT_LANGUAGE_ATTRIBUTE",
				"english");
		System.out.println("DEFAULT LANGUAGE INITIALIZED");
	}

	public void contextDestroyed(ServletContextEvent sce) {
		System.out.println("CONTEXT DESTROYED");
	}

}

In this example we are setting the default language to be used throughout the application. Here we have hardcoded the value but in actual implementation we normally read these values from a properties file. The application context is initialized with the " DEFAULT_LANGUAGE_ATTRIBUTE" as "english". This context attribute is used throughout the life cycle of the application, till the time, the context is destroyed. The following code shows how the context value "DEFAULT_LANGUAGE_ATTRIBUTE" is used in other parts of the application.

Listing 4: Using the context attribute

package com.home.servletlisteners;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class TestServlet extends HttpServlet {

	protected void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String attr = (String) getServletContext().getAttribute(
				"DEFAULT_LANGUAGE_ATTRIBUTE");
		System.out.println("CONTEXT ATTRIBUTE DEFAULT LANGUAGE : " + attr);
	}

	@Override
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	@Override
	public String getServletInfo() {
		return "Description about the servlet";
	}
}

Also we should define the context listener in the web.xml as under:

<?xml version="1.0" encoding="UTF-8"?> 
<web-app version="2.5" 
	xmlns="http://java.sun.com/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<listener>
        <listener-class>com.home.servletlisteners.SampleServletContextListener</listener-class>
    </listener>
</web-app>

Advantages of Servlet Context

Servlet context has the following advantages:

  • Easy to define : As we have seen above defining servlet context is pretty straight forward and is just like defining any attribute in a java program.
  • Easy to maintain: Servlet Context objects are easy to maintain as they need to be defined at a single place and change at only place if required.
  • Easy to destroy: Servlet context is not only easy to define and maintain, it is also easy to destroy a servlet.

Usage of Servlet Context

Servlet context has a lot of usage. Some of them are listed below:

  • The servlet context object provides an interface between the container and the servlet.
  • The servlet context object is used to get the configuration information from the deployment descriptor file which is web.xml in case of java based web applications.
  • The servlet context object is also used to get set or remove attribute from the web.xml file.
  • The servlet context object is also used to facilitate the inter-application communication i.e. it helps in communicating with other applications which are based on similar technology.

The following picture shows the architecture of the servlet context and how it interacts with the other components of the web application :

Webserver architecture

Figure 1: Webserver architecture

Conclusion

Let us summarize to what we have discussed so far about the servlet context listener and its usage in the following bullets:

  • Servlet context listener is an interface which receives the notification events about the life cycle of the servlets.
  • Servlet context is created when we deploy the web application.
  • Once created, the servlet context object is available throughout the life cycle of the application.
  • Class implementing the servlet context listener interface must provide implementation for contextInitialized() and
  • contextDestroyed() methods.
  • Some examples of Servlet context listener implementation are as under:
    • Setting up the default language for the application.
    • Setting up the database parameters for an application.
    • Reading other parameters from resource files which are required by the application.


Website: www.techalpine.com Have 16 years of experience as a technical architect and software consultant in enterprise application and product development. Have interest in new technology and innovation area along with technical...

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login