javax.servlet.ServletContextListener :-


ServletContextListener interface gets notified when servlet context created or destroyed. You can use it to know if a context has been created or destroyed.
It has following methods -

1- contextInitialized() - This method invokes when web-app initialization process starts. It has the following syntax -
public void contextInitialized(ServletContextEvent event)        

2- contextDestroyed() - This method invokes just before ServletContext destroyed. It has the following syntax -
public void contextDestroyed(ServletContextEvent event)        

ServletContextEvent -

javax.servlet.ServletContextEvent is an event class corresponding to ServletContextListener. It sends notification whenever ServletContext intializzed or destroyed.
It has the following method -

1- getServletContext() - It returns the ServletContext object. It has the following syntax -
public ServletContext getServletContext()        



Example -

This example will make use of ServletContextListener for counting total hits on your website. Because one ServletContext is created for whole web-app and it is shared by all the resources (servlet's and jsp's), So to count total hits on all the pages in our web-app, we can add a attribute to ServletContext and gets it incremented each time user visits a page.

1 - index.html or index.jsp - This will be your default page.
<!DOCTYPE html>
<html>
    <head>
        <title>ServletContextListener Demo</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body>
        <a href="First">FirstPage</a><br>
        <a href="Second">SecondPage</a><br>
        <a href="Info">Show total hits</a><br>        
    </body>
</html>
    

2- Create a package named serv and within that create the following servlets -
First Servlet -

package servs;

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

public class First extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        try
        {
            PrintWriter out = response.getWriter();
            out.println("<h1>My First Page</h1>");
            ServletContext application = getServletConfig().getServletContext();

            // get and increment context attribute named Total_Hits
            Integer val = (Integer)application.getAttribute("Total_Hits");
            val++;
            application.setAttribute("Total_Hits", val);
        }
        catch(Exception ex)
        {
            System.out.println(ex);
        }
    }
}

Second Servlet -

package servs;

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

public class Second extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        try
        {
            PrintWriter out = response.getWriter();
            out.println("<h1>My Second Page</h1>");

            // get and increment context attribute named Total_Hits
            ServletContext application = getServletConfig().getServletContext();
            Integer val = (Integer)application.getAttribute("Total_Hits");
            val++;
            application.setAttribute("Total_Hits", val);
        }
        catch(Exception ex)
        {
            System.out.println(ex);
        }
    }
}         

Info Servlet - This servlet display the value of Total_Hits Context attribute.
package servs;

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

public class Info extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        try
        {
            PrintWriter out = response.getWriter();
            ServletContext application = getServletConfig().getServletContext();
            out.println("Total hits on your website - "+ application.getAttribute("Total_Hits").toString());
        }
        catch(Exception ex)
        {
            System.out.println(ex);
        }
    }
}        
3- Create a package named listeners and within that create a class named MyListener_1 that will work as a ServletContextListener -
package listeners;

import javax.servlet.*;

public class MyListener_1 implements ServletContextListener {

    public void contextInitialized(ServletContextEvent event) 
    {
        ServletContext application = event.getServletContext();
        
        /*Add an attribute to ServletContext, that can be used by all the servlet's
          and jsp's in your web-app.  */
        application.setAttribute("Total_Hits", 0);
    }

    public void contextDestroyed(ServletContextEvent event)
    {
    }
}


4- web.xml - Add the information of servlet and listener in web.xml file -
<web-app>
    <listener>
        <listener-class>listeners.MyListener_1</listener-class>
    </listener>
    <servlet>
        <servlet-name>First</servlet-name>
        <servlet-class>servs.First</servlet-class>
    </servlet>
      <servlet-mapping>
        <servlet-name>First</servlet-name>
        <url-pattern>/First</url-pattern>
    </servlet-mapping>
    <servlet>
        <servlet-name>Second</servlet-name>
        <servlet-class>servs.Second</servlet-class>
    </servlet>
     <servlet-mapping>
        <servlet-name>Second</servlet-name>
        <url-pattern>/Second</url-pattern>
    </servlet-mapping>
    <servlet>
        <servlet-name>Info</servlet-name>
        <servlet-class>servs.Info</servlet-class>
    </servlet>
        <servlet-mapping>
        <servlet-name>Info</servlet-name>
        <url-pattern>/Info</url-pattern>
    </servlet-mapping>
</web-app>        


5- Now run the project, It will show you index page -



Click on the First and Second page links multiple times and finally click on 'Show total hits' link and it will show you how many time you have hits the pages - .