Updates
  • Starting New Weekday Batch for Full Stack Java Development on 13 October 2025 @ 10:00 AM to 12:00 PM
  • Starting New Weekday Batch for MERN Stack Development on 13 October 2025 @ 04:00 PM to 06:00 PM

Listener

• When your web application is running in the web container, the following tasks will be done by the web container and developer.

1. Creating ServletContext object
2. Destroying ServletContext object
3. Creating HttpServletRequest object
4. Destroying HttpServletRequest object
5. Creating HttpSession object
6. Destroying HttpSession object
7. Adding attributes to ServletContext.
8. Removing Attributes from ServletContext
9. Replacing attributes from ServletContext
10. Adding attributes to HttpServletRequest
11. Removing Attributes from HttpServletRequest
12. Replacing attributes from HttpServletRequest
13. Adding attributes to HttpSession
14. Removing Attributes from HttpSession
15. Replacing attributes from HttpSession
16. Passivating HttpSession object
17. Activating HttpSession object

• Following is the list of Listener interfaces available in Servlet via the Servlet API.

Listerner Interface Event Class Task will be listened
ServletContextListener ServletContextEvent Task 1, Task 2
ServletRequestListener ServletRequestEvent Task 3,Task 4
HttpSessionListener HttpSessionEvent Task 5, Task 6
ServletContextAttributeListener ServletContextAttributeEvent Task 7, Task 8, Task 9
ServletRequestAttributeListener ServletRequestAttributeEvent Task 10, Task 11,Task 12
HttpSessionAttributeListener HttpSessionBindingEvent Task 13,Task 14,Task15
HttpSessionBindingListener HttpSessionBIndingEvent
HttpSessionActivationListener HttpSessionEvent Task 16,Task 17
Steps to write the Listener with Servlet 2.x

• Write your own listener class by implementing the required Listener interface.
• Override the responding methods of the listener interface that you are implementing.

Class MyListner implements ServletContextListener{
  Public void contextInitialized(sce){
    //your code here
    }
  Public void contextDestroyed(sce){
    //your code here
  Ctx=sce.getServletContext();
  }
}

• Register the listener by writing the following in web.xml:

<listener> <listener-class>com.jtc.MyListener</listener-class> </listener>

Steps to write the Listener with Servlet 3.0

• Write your own listener class by implementing the required Listener interface.
• Override the corresponding methods of the Listener interface that you are implementing.
• Register the listing by using @WebListener annonation.

 @webListerner
   Class MyListner implements ServletContextListener{
   Public void contextInitialized(sce){
    //your code here
      }
   Public void contextDestroyed(sce){
    //your code here
   Ctx=sce.getServletContext();
  }
 }

Note: All the listeners configured will be initialised by the container at container start-up.

Container Tasks at Container Start-up

• Creates the ServletContext object.

o ServletContext sctx=new ServlletContextImpl();

• Gets the context parameters from web.xml and stores them in a ServletContext object.
• Creates a ServletContextEvent

o ServletContextEventListener sce=new ServletContextEvent(sctx);

• Create the ServletContextListener object.

o ServletContextListener listner = new ServletContextListenerImple();

• Invoke the contextinitialized() method with the ServletContextListerner object.

o Listener.contextInitialized(sce).

Container Tasks at Container Shutdown Time.

• Invoke the contextDestroyed() method with ServletContextListener object

o Listener.contextDestoryed(sce).

• Destroys the ServletContext object.

File Required For Program

1. Index.html
2. TestServlet.java
3. MyContextListener.java
4. MyContextAttributeListerner.java
5. MySessionListener.java
6. MyRequestListener.java
7. Web.xml

1. Index.html

            
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML4.01 Transitional//EN""http://www.w3.org/TR/html4/loose.dtd">
<html>
   <head>
      <meta http-equiv="Content-Type"
         content="text/html; charset=ISO-8859-
         1">
      <title>Insert title here</title>
   </head>
   <body>
      <h1>JTC</h1>
      <h2>Listener Example</h2>
      <form action="test.jtc" method="post">
         Enter Email:<input type="text"
            name="email">
         <br/>
         <input type="submit" value="submit">
      </form>
   </body>
</html>
        
            

2. TestServlet.java

            
package com.jtcindia.Servlet;
import java.io.IOException;
import java.io.Writer;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/*
 * @Author : Som Prakash Rai
 * @Join : JTC
 * @visit : www.jtcindia.org
 *@Call :+91-9990399111
 * */
public class TestServlet extends HttpServlet {
   @Override
   protected void service(HttpServletRequest req, HttpServletResponse res)
   throws ServletException, IOException {
      System.out.println("TestServlet-> service()");
      System.out.println("Acccessing Session object");
      HttpSession session = req.getSession();
      String eml = req.getParameter("email");
      ServletContext ctx = getServletContext();
      System.out.println("Storing attribute in Context");
      ctx.setAttribute("email", eml);
      System.out.println("Replacing attributes in Context");
      ctx.setAttribute("email", "som@jtc.com");
      System.out.println("Removing attribute in Context");
      ctx.removeAttribute("email");
      System.out.println("validating Session Objects");
      session.invalidate();
      Writer out = res.getWriter();
      out.write("<h1>Verify the server console");
   }
}
        
            

3. MyContextListener.java

            
package com.jtcindia.Servlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
/*
 * @Author : Som Prakash Rai
 * @Join : JTC
 * @visit : www.jtcindia.org
 *@Call :+91-9990399111
 * */
public class MyContextListener implements
ServletContextListener {
   public MyContextListener() {
      System.out.println("** MyContextListener() def
         consol ");
      }
      @Override
      public void contextDestroyed(ServletContextEvent event) {
         ServletContext
         ctx = event.getServletContext();
         System.out.println("ContextDestroyed:" + ctx);
      }
      @Override
      public void contextInitialized(ServletContextEvent event) {
         ServletContext
         ctx = event.getServletContext();
         System.out.println("ContextInitialized:" + ctx);
      }
   }
        
            

4. MyContextAttributeListener.java

            
package com.jtcindia.Servlet;
import javax.servlet.ServletContextAttributeEvent;
import javax.servlet.ServletContextAttributeListener;
/*
 * @Author : Som Prakash Rai
 * @Join : JTC
 * @visit : www.jtcindia.org
 *@Call :+91-9990399111
 * */
public class MyContextAttributListener implements
ServletContextAttributeListener {
   public MyContextAttributListener() {
         System.out.println("** MyContextAttributListener()
            Def Console ");
         }
         @Override
         public void
         attributeAdded(ServletContextAttributeEvent event) {
            String nm = event.getName();
            String val = event.getValue().toString();
            System.out.println("**
               AttributeAdded(): "+nm+"\
               t "+val);
            }
            @Override
            public void
            attributeRemoved(ServletContextAttributeEvent event) {
               String nm = event.getName();
               String val = event.getValue().toString();
               System.out.println("attributeRemove():" + n m + "\t" + val)
            }
            @Override
            public void
            attributeReplaced(ServletContextAttributeEvent event) {
               String nm = event.getName();
               String val = event.getValue().toString();
               System.out.println("attributeRemove():" + n m + "\t" + val);
            }
         }
        
            

5. MySessionListener.java

            
package com.jtcindia.Servlet;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
/*
 * @Author : Som Prakash Rai
 * @Join : JTC
 * @visit : www.jtcindia.org
 *@Call :+91-9990399111
 * */
public class MySessionListener implements
HttpSessionListener {
   public MySessionListener() {
      System.out.println("**
         MySessionListener() def Cons ");
      }
      @Override
      public void sessionCreated(HttpSessionEvent arg0) {
         System.out.println("SessionCreated");
      }
      @Override
      public void sessionDestroyed(HttpSessionEvent arg0) {
         System.out.println("**SessionDestroyed");
      }
   }
        
            

6. MyRequestListener.java

            
package com.jtcindia.Servlet;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
/*
 * @Author : Som Prakash Rai
 * @Join : Java Training Center
 * @visit : www.jtcindia.org
 *@Call :+91-9990399111
 * */
public class MyRequestListener implements
ServletRequestListener {
   public MyRequestListener() {
      System.out.println("MyRequestListener()
         def console ");
      }
      @Override
      public void
      requestDestroyed(ServletRequestEvent arg0) {
         System.out.println("requestDestroyed");
      }
      @Override
      public void
      requestInitialized(ServletRequestEvent arg0) {
         System.out.println("requestInitialized");
      }
   }
        
            

7. Web.xml

            
<?xml version="1.0" encoding="UTF-8"?>
<web-appxmlns:xsi="http://www.w3.org/2001/XMLSchemainstance" xmlns="http://java.sun.com/xml/ns/javaee"
   xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
   id="WebApp_ID" version="3.0">
   <display-name>Jtc27</display-name>
   <welcome-file-list>
      <welcome-file>index.html</welcome-file>
   </welcome-file-list>
   <servlet>
      <servlet-name>testServlet</servlet-name>
      <servletclass>com.jtcindia.Servlet.TestServlet</servletclass>
   </servlet>
   <servlet-mapping>
      <servlet-name>testServlet</servlet-name>
      <url-pattern>/test.jtc</url-pattern>
   </servlet-mapping>
   <listener>
      <listenerclass>com.jtcindia.Servlet.MyContextListener</listener-class>
   </listener>
   <listener>
      <listenerclass>com.jtcindia.Servlet.MyContextAttributListener
      </listener-class>
   </listener>
   <listener>
      <listenerclass>com.jtcindia.Servlet.MyRequestListener</listener-class>
   </listener>
   <listener>
      <listenerclass>com.jtcindia.Servlet.MySessionListener</listener-class>
   </listener>
</web-app>