Servlet - Context Event and Context Listener
Last Updated :
24 Mar, 2022
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
Method
| 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
HTML
<a href="CounterGfg">Total Page views GeeksforGeeks</a>
B. File: web.xml

XML
<web-app>
<listener>
<listener-class>MyListenerGfg</listener-class>
</listener>
<servlet>
<servlet-name>CounterGfg</servlet-name>
<servlet-class>CounterGfg</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>CounterGfg</servlet-name>
<url-pattern>/CounterGfg</url-pattern>
</servlet-mapping>
</web-app>
C. File: MyListenerGfg.java
Java
// 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
Class.forName("com.mysql.jdbc.Driver");
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 (rs.next()) {
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
e.printStackTrace();
}
}
// Method 2
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();
}
}
}
D. File: CounterGfg.java
Java
// Java Program to Illustrate Counter Class
// Importing required classes
import java.io.*;
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
{
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);
}
}
Now, run 'index.html' file on server and this will show the following output
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.

Similar Reads
Servlet - Event and Listener The term "event" refers to the occurrence of something. An event occurs when the state of an object changes. When these exceptions occur, we can conduct certain crucial actions, such as collecting total and current logged-in users, establishing database tables when deploying the project, building da
8 min read
Servlet - HttpSessionEvent and HttpSessionListener In Java, HttpSessionEvent is a class, which is representing event notifications for changes or updates to sessions within a web application. Similarly, the interface for this event is HttpSessionListener, which is for receiving notification events about HttpSession lifecycle changes. As a means to,
3 min read
How to Create an Event Listener in Applet? In this article, we will be creating the event Listener in the Applet window. Here, we will use the ActionListener on Button and MouseListener when the event has occurred through mouse activities. Approach for Implementing Event Listener AppletWe need to import the essential packages like Applet and
5 min read
Difference between Applets and Servlets Prerequisite: Servlets and Applets AppletsServletsA Java applet is a small application which is written in Java and delivered to users in the form of bytecode.A servlet is a Java programming language class used to extend the capabilities of a server.Applets are executed on client side.Servlets are e
2 min read
ContextLoaderListener vs DispatcherServlet ContextLoaderListener and DispatcherServlet are two declarations that you should have seen in the web.xml file while configuring Spring MVC using XML. Let's attempt to comprehend their distinctions and their usefulness inside the framework.ContextLoaderListener adds the web application's root contex
3 min read