Servlet context listeners – How to use?

Servlet

Servlet

მიმოხილვა: 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;

იმპორტი javax.servlet.ServletContextEvent;

იმპორტი javax.servlet.ServletContextListener;

იმპორტი com.home.hibernate.HibernateUtil;

საჯარო კლასის HibernateContextListener implements ServletContextListener{

საჯარო ცნოს contextInitialized(ServletContextEvent sce) {

HibernateUtil.initSessionFactory();

სისტემები.გარეთ.println(“HIBERNATE SESSION FACTORY INITIALIZED”);

}

საჯარო ცნოს contextDestroyed(ServletContextEvent sce) {

თუ (HibernateUtil.getSessionFactory()!=ნულოვანი) {

HibernateUtil.getSessionFactory().close();

}

სისტემები.გარეთ.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;

იმპორტი org.hibernate.SessionFactory;

იმპორტი org.hibernate.cfg.Configuration;

საჯარო კლასის HibernateUtil {

შეტყობინების სტატიკური SessionFactory sessionFactory;

/**

* Initializes the Hibernate SessionFactory.

*/

საჯარო სტატიკური synchronized ცნოს initSessionFactory() {

თუ (getSessionFactory() != ნულოვანი) {

throw ახალი IllegalStateException(

“Hibernate SessionFactory is already initialized”);

}

ვცდილობთ {

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

sessionFactory = ახალი Configuration().configure().buildSessionFactory();

} catch (Exception e) {

throw ახალი ExceptionInInitializerError(და);

}

}

საჯარო სტატიკური synchronized SessionFactory getSessionFactory() {

ვცდილობთ {

sessionFactory = ახალი Configuration().configure()

.buildSessionFactory();

} catch (Throwable ex) {

სისტემები.err.println(“Failed to create sessionFactory object.” + ex);

throw ახალი 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;

იმპორტი javax.servlet.ServletContextEvent;

იმპორტი javax.servlet.ServletContextListener;

საჯარო კლასის SampleServletContextListener implements ServletContextListener {

საჯარო ცნოს contextInitialized(ServletContextEvent sce) {

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

“english”);

სისტემები.გარეთ.println(“DEFAULT LANGUAGE INITIALIZED”);

}

საჯარო ცნოს contextDestroyed(ServletContextEvent sce) {

სისტემები.გარეთ.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;

იმპორტი java.io.IOException;

იმპორტი javax.servlet.ServletException;

იმპორტი javax.servlet.http.HttpServlet;

იმპორტი javax.servlet.http.HttpServletRequest;

იმპორტი javax.servlet.http.HttpServletResponse;

საჯარო კლასის TestServlet ვრცელდება HttpServlet {

protected ცნოს processRequest(HttpServletRequest მოთხოვნა,

HttpServletResponse პასუხი) ისვრის ServletException, IOException {

String attr = (სიმებიანი) getServletContext().getAttribute(

“DEFAULT_LANGUAGE_ATTRIBUTE”);

სისტემები.გარეთ.println(“CONTEXT ATTRIBUTE DEFAULT LANGUAGE : ” + attr);

}

@ Override

protected ცნოს doGet(HttpServletRequest მოთხოვნა,

HttpServletResponse პასუხი) ისვრის ServletException, IOException {

processRequest(request, response);

}

@ Override

protected ცნოს doPost(HttpServletRequest მოთხოვნა,

HttpServletResponse პასუხი) ისვრის ServletException, IOException {

processRequest(request, response);

}

@ Override

საჯარო 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.

 

 

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

Enjoy this blog? Please spread the word :)

Follow by Email
LinkedIn
LinkedIn
Share