Servlet context listeners – How to use?

Servlet

Servlet

Übersicht: 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

[Code]

package com.home.servletlisteners;

importieren javax.servlet.ServletContextEvent;

importieren javax.servlet.ServletContextListener;

importieren com.home.hibernate.HibernateUtil;

Öffentlichkeit Klasse HibernateContextListener implements ServletContextListener{

Öffentlichkeit ungültig contextInitialized(ServletContextEvent sce) {

HibernateUtil.initSessionFactory();

System.heraus.println(“HIBERNATE SESSION FACTORY INITIALIZED”);

}

Öffentlichkeit ungültig contextDestroyed(ServletContextEvent sce) {

wenn (HibernateUtil.getSessionFactory()!=null) {

HibernateUtil.getSessionFactory().close();

}

System.heraus.println(“HIBERNATE SESSION FACTORY DESTROYED”);

}

}

[/Code]

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

[Code]

package com.home.hibernate;

importieren org.hibernate.SessionFactory;

importieren org.hibernate.cfg.Configuration;

Öffentlichkeit Klasse HibernateUtil {

Private statische SessionFactory sessionFactory;

/**

* Initializes the Hibernate SessionFactory.

*/

Öffentlichkeit statische synchronized ungültig initSessionFactory() {

wenn (getSessionFactory() != null) {

throw neue IllegalStateException(

“Hibernate SessionFactory is already initialized”);

}

versuchen {

// Create the SessionFactory from the hibernate.cfg.xml

sessionFactory = neue Configuration().configure().buildSessionFactory();

} fangen (Exception e) {

throw neue ExceptionInInitializerError(und);

}

}

Öffentlichkeit statische synchronized SessionFactory getSessionFactory() {

versuchen {

sessionFactory = neue Configuration().configure()

.buildSessionFactory();

} fangen (Throwable ex) {

System.err.println(“Failed to create sessionFactory object.” + ex);

throw neue ExceptionInInitializerError(ex);

}

return sessionFactory;

}

}

[/Code]
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

[Code]

package com.home.servletlisteners;

importieren javax.servlet.ServletContextEvent;

importieren javax.servlet.ServletContextListener;

Öffentlichkeit Klasse SampleServletContextListener implements ServletContextListener {

Öffentlichkeit ungültig contextInitialized(ServletContextEvent sce) {

sce.getServletContext().setAttribute(“DEFAULT_LANGUAGE_ATTRIBUTE”,

“english”);

System.heraus.println(“DEFAULT LANGUAGE INITIALIZED”);

}

Öffentlichkeit ungültig contextDestroyed(ServletContextEvent sce) {

System.heraus.println(“CONTEXT DESTROYED”);

}

}

[/Code]
In this example we are setting the default language to be used throughout the application. Here we have hard coded 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

[Code]

package com.home.servletlisteners;

importieren java.io.IOException;

importieren javax.servlet.ServletException;

importieren javax.servlet.http.HttpServlet;

importieren javax.servlet.http.HttpServletRequest;

importieren javax.servlet.http.HttpServletResponse;

Öffentlichkeit Klasse TestServlet erstreckt HttpServlet {

protected ungültig processRequest(HttpServletRequest Anfrage,

HttpServletResponse Antwort) wirft ServletException, IOException {

String attr = (Schnur) getServletContext().getAttribute(

“DEFAULT_LANGUAGE_ATTRIBUTE”);

System.heraus.println(“CONTEXT ATTRIBUTE DEFAULT LANGUAGE : ” + attr);

}

@ Override

protected ungültig doGet(HttpServletRequest Anfrage,

HttpServletResponse Antwort) wirft ServletException, IOException {

processRequest(request, response);

}

@ Override

protected ungültig doPost(HttpServletRequest Anfrage,

HttpServletResponse Antwort) wirft ServletException, IOException {

processRequest(request, response);

}

@ Override

Öffentlichkeit String getServletInfo() {

return “Description about the servlet”;

}

}

[/Code]

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

[Code]

<?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>

[/Code]

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

web server-architecture

Figure 1: Web server architecture

Summary:
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.

 

 

Stichworte:,
============================================= ============================================== Buy best TechAlpine Books on Amazon
============================================== ---------------------------------------------------------------- electrician ct chestnutelectric
error

Enjoy this blog? Please spread the word :)

Follow by Email
LinkedIn
LinkedIn
Share