Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App

Related Articles

Servlet – Context Event and Context Listener

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

ServletContextEvent class provides alerts/notifications for changes to a web application’s servlet context. ServletContextListener is a class that receives alerts/notifications about changes to the servlet context and acts on them. When the context is initialized and deleted, the ServletContextListener is utilized to conduct crucial tasks. In a nutshell, ServletContextEvent and ServletContextListener function in tandem; anytime the ServletContext changes, ServletContextEvent broadcasts a notice, which is received by ServletContextListener, which then performs various duties based on the message.

Constructor of ServletContextEvent Class

ServletContextEvent(ServletContext e)

In the ServletContextEvent class, there is just one constructor. After the ServletContext instantiation, the web container produces an instance of ServletContextEvent.

Methods of ServletContextEvent

public ServletContext getServletContext()

Note: It returns the instance of ServletContext.

Methods of ServletContextListener Interface


Action Performed 

void contextInitialized(ServletContextEvent e)When the application is first initialized, this method is called.
void contextDestroyed(ServletContextEvent e)When the application is destroyed, this method is called.

Example: ServletContextEvent and ServletContextListener

In this example, we will have to create a table named counter with a column named pageview to save the number of pageviews. by using this database record we will find out the total number of page views.

A. File: index.html


<a href="CounterGfg">Total Page views GeeksforGeeks</a>

B. File: web.xml



C. File:


// Java Program to Illustrate MyListener Class
// Importing required classes
import java.sql.*;
import javax.servlet.*;
// Class
public class MyListenerGfg implements ServletContextListener {
    // Class data members
    ServletContext ctx;
    Connection con;
    Statement s;
    PreparedStatement ps;
    ResultSet rs;
    int count;
    // Method 1
    public void contextInitialized(ServletContextEvent sce) {
        // Try block to check for exceptions
        try {
            // Loading drivers using forName() method
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/geeksforgeeks", "root", "root");
            s = con.createStatement();
            // Fetching pageviews value from table counter
            rs = s.executeQuery("select pageview from counter");
            // Iterating using next() method
            while ( {
                count = rs.getInt(1);
            ctx = sce.getServletContext();
            ctx.setAttribute("pcount", count);
        // Catch block to handle exceptions
        catch (Exception e) {
            // Display exception with line number
            // using printStackTrace() method
    // Method 2
    public void contextDestroyed(ServletContextEvent sce) {
        try {
            ctx = sce.getServletContext();
            count = (Integer)ctx.getAttribute("pcount");
            ps = con.prepareStatement("update counter set pcount='" + count + "'");
        catch (Exception e) {

D. File:


// Java Program to Illustrate Counter Class
// Importing required classes
import javax.servlet.*;
import javax.servlet.http.*;
// Class
// Extending HttpServlet class
public class CounterGfg extends HttpServlet {
    // Method
    protected void doGet(HttpServletRequest request,
                         HttpServletResponse response)
        throws ServletException, IOException
        PrintWriter out = response.getWriter();
        ServletContext ctx = getServletContext();
        Integer count = (Integer)ctx.getAttribute("pcount");
        out.println(count + ": pageview");
        ctx.setAttribute("pcount", ++count);

Now, run ‘index.html’ file on server and this will show the following output


After clicking on that link following page will be loaded which shows the count of page views means how many times the user visited the page. The page count will be increased every time you refresh or revisit the page.

My Personal Notes arrow_drop_up
Last Updated : 24 Mar, 2022
Like Article
Save Article
Similar Reads
Related Tutorials