15 - Servlet Listeners

15.1 Overview

Listeners are the classes which listens to a particular type of events and when that event occurs , triggers the functionality. Each type of listener is bind to a type of event. In this chapter we will discuss the types of listeners supported by servlet framework.

15.2 Listeners

There are total eight type of listeners available in servlet framework which listens to a particular event and they are –

  • ServletContextListener
  • ServletContextAttributeListener
  • HttpSessionListener
  • HttpSessionAttributeListener
  • ServletRequestListener
  • ServletRequestAttributeListener
  • HttpSessionActivationListener
  • HttpSessionBindingListener

As the configurations of servlets , filters goes inside web.xml , similarly listeners are also configured inside web.xml using <listener> </listener> tag.

Note – Listeners are neither a Servlets nor a JSP.

15.2.1 ServletContextListener

ServletContextListener listens to SessionContextEvent event which gives a notification when Servlet Context is initialized or destroyed and ased on the events ServletContextListener executes the functionality.

ServletContextListener  is the interface and it defines two methods –

  • void contextDestroyed(ServletContextEvent e) – This method is executed when application is destroyed
  • void contextInitialized(ServletContextEvent e)- This method is executed when application is initialized

ServletContext object can be obtained from  ServletContextEvent and listener can set the attributes in Servlet context object which can be used in servlets later.

We can use the “ServletContextListener “  listener for any activity that is required either at the application deployment time  or any clean up activity required  when application is destroyed. One of the practical example that I can think of is initializing database connections and clean up of database connections.

Let s write a sample listener which will print some message describing the event and store one attribute in context which will be read by servlet

  1. Add listener entry in web.xml
    <listener>
     <description>Servlet Context Listener Example</description>
     <listener-class>com.servlet.tutorial.MyServletContextListener</listener-class>
    </listener>
    
    
  1. Write MyServletContextListener code
package com.servlet.tutorial;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class MyServletContextListener implements ServletContextListener {
    /**
     * Default constructor. 
     */
    public MyServletContextListener() {
    }
    private ServletContext context;
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        System.out.println("Context Initialized");
        // get servlet context
        context =servletContextEvent.getServletContext();
        // set attribute in context
        String attributeValue = "Context Param Value";
        String attributeName ="ContextParam";
        context.setAttribute(attributeName, attributeValue);
    }
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        System.out.println("Context Destroyed");
    }
}

  1. Add entry  of servlet in web.xml
<servlet>
    <servlet-name>MyServlet</servlet-name>
    <servlet-class>com.servlet.tutorial.MyServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>MyServlet</servlet-name>
    <url-pattern>/MyServlet</url-pattern>
 </servlet-mapping>

  1. Write MyServlet Code
package com.servlet.tutorial;
import java.io.IOException;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MyServlet extends HttpServlet {    
    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException
    {                                                      
        ServletContext ctx = getServletContext();          
        System.out.println(ctx.getAttribute("ContextParam"));
    }                                              
}

Testing –

When the application is deployed message will be displayed on server console

Hit http://localhost:8080/HelloWorld/MyServlet , context param value will be printed on console

Un-deploy the web application, contexDestroyed method will be executed

Like us on Facebook