Servlet context listeners – How to use?

Servlet

Servlet

Pārskats: 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;

importēt javax.servlet.ServletContextEvent;

importēt javax.servlet.ServletContextListener;

importēt com.home.hibernate.HibernateUtil;

valsts klase HibernateContextListener implements ServletContextListener{

valsts par spēkā neesošu contextInitialized(ServletContextEvent sce) {

HibernateUtil.initSessionFactory();

Sistēma.ārā.println(“HIBERNATE SESSION FACTORY INITIALIZED”);

}

valsts par spēkā neesošu contextDestroyed(ServletContextEvent sce) {

ja (HibernateUtil.getSessionFactory()!=nulle) {

HibernateUtil.getSessionFactory().close();

}

Sistēma.ārā.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;

importēt org.hibernate.SessionFactory;

importēt org.hibernate.cfg.Configuration;

valsts klase HibernateUtil {

privāts statisks SessionFactory sessionFactory;

/**

* Initializes the Hibernate SessionFactory.

*/

valsts statisks synchronized par spēkā neesošu initSessionFactory() {

ja (getSessionFactory() != nulle) {

throw jauns IllegalStateException(

“Hibernate SessionFactory is already initialized”);

}

izmēģināt {

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

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

} noķert (Exception e) {

throw jauns ExceptionInInitializerError(un);

}

}

valsts statisks synchronized SessionFactory getSessionFactory() {

izmēģināt {

sessionFactory = jauns Configuration().configure()

.buildSessionFactory();

} noķert (Throwable ex) {

Sistēma.err.println(“Failed to create sessionFactory object.” + ex);

throw jauns 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;

importēt javax.servlet.ServletContextEvent;

importēt javax.servlet.ServletContextListener;

valsts klase SampleServletContextListener implements ServletContextListener {

valsts par spēkā neesošu contextInitialized(ServletContextEvent sce) {

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

“english”);

Sistēma.ārā.println(“DEFAULT LANGUAGE INITIALIZED”);

}

valsts par spēkā neesošu contextDestroyed(ServletContextEvent sce) {

Sistēma.ārā.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;

importēt java.io.IOException;

importēt javax.servlet.ServletException;

importēt javax.servlet.http.HttpServlet;

importēt javax.servlet.http.HttpServletRequest;

importēt javax.servlet.http.HttpServletResponse;

valsts klase TestServlet paplašina HttpServlet {

protected par spēkā neesošu processRequest(HttpServletRequest request,

HttpServletResponse response) throws ServletException, IOException {

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

“DEFAULT_LANGUAGE_ATTRIBUTE”);

Sistēma.ārā.println(“CONTEXT ATTRIBUTE DEFAULT LANGUAGE : ” + attr);

}

@ Ignorēšana

protected par spēkā neesošu doGet(HttpServletRequest request,

HttpServletResponse response) throws ServletException, IOException {

processRequest(request, response);

}

@ Ignorēšana

protected par spēkā neesošu doPost(HttpServletRequest request,

HttpServletResponse response) throws ServletException, IOException {

processRequest(request, response);

}

@ Ignorēšana

valsts 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: ,
============================================= ============================================== Pērciet labākās Techalpine grāmatas vietnē Amazon,en,Elektriķa CT kastaņu valodas,en
============================================== ---------------------------------------------------------------- electrician ct chestnutelectric
error

Enjoy this blog? Please spread the word :)

Follow by Email
LinkedIn
LinkedIn
Share