Signup/Sign In

ServletContextEvent and ServletContextListener in Servlet

ServletContextEvent class gives notifications about changes to the servlet context of a web application. ServletContextListener receives the notifications about changes to the servlet context and perform some action. ServletContextListener is used to perform important task at the time when context is initialized and destroyed. In short, ServletContextEvent and ServletContextListener works in pair, whenever Servlet COntext changes, ServletContextEvent publishes a notification which is received by ServletContextListener and then, based on that certain tasks are performed by it.


Methods of ServletContextListener Interface

MethodsDescription
void contextDestroyed(ServletContextEvent e) is invoked when the application is destroyed.
void contextInitialized(ServletContextEvent e)is invoked when the application is initialized.

Making and Using a context listener

Context listener is not a servlet or JSP, it's a class that implements ServletContextListener interface and provides definition of contextDestroyed() and contextInitialized().

Using a ServletContextListener


Example demontrating usage of ServletContextListener


index.html


<a href="Counter">Total Page views</a>

web.xml

Using a ServletContextListener in web xml


For this example we will have to create a table named counter with a column named pageview to save the number of pageviews.

MyListener.java

import java.sql.*;
import javax.servlet.*;

public class MyListener implements ServletContextListener
{
    ServletContext ctx;
    Connection con;
    Statement s;
    PreparedStatement ps;
    ResultSet rs;
    int count;
    
    public void contextInitialized(ServletContextEvent sce) {
    
        try {
            Class.forName("com.mysql.jdbc.Driver");
     	      con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","user","password");

            s = con.createStatement();
      
            // fetching pageviews value from table counter
            rs = s.executeQuery("select pageview from counter");
            
            while(rs.next()) {
                count = rs.getInt(1);
            }
       
            ctx = sce.getServletContext();
            ctx.setAttribute("pcount", count);
        }
        catch(Exception e) { 
            e.printStackTrace(); 
        }  
    }

    public void contextDestroyed(ServletContextEvent sce) {
   
        try
        {
            ctx = sce.getServletContext();
            count = (Integer)ctx.getAttribute("pcount");
            ps = con.prepareStatement("update counter set pcount='"+count+"'");
            ps.executeUpdate(); 
        } 
        catch(Exception e) { 
            e.printStackTrace(); 
        }
    }   
}

Counter.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class Counter extends HttpServlet {
   
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        ServletContext ctx = getServletContext();
        Integer count = (Integer)ctx.getAttribute("pcount");
        out.println(count+": pageview");
        ctx.setAttribute("pcount", ++count);      
    }
}