ServletContextEvent and ServletContextListener are used to monitor and handle important activities occurring inside a web application such as application startup, context initialization, and application shutdown. They allow developers to execute custom logic automatically whenever a specific event occurs in the servlet container.
- ServletContextEvent represents changes or actions occurring in the ServletContext.
- ServletContextListener is a special class that automatically responds to these context events.
- They are commonly used for database initialization, logging, resource management, and application-level tracking.
Event Categories
Servlet Context events are mainly divided into two categories:
1. Context Lifecycle Events
These events occur when the web application is started or stopped.
- contextInitialized -> triggered when application starts
- contextDestroyed -> triggered when application stops
2. Context Attribute Events
These events occur when attributes are added, removed, or modified in ServletContext.
- attributeAdded
- attributeRemoved
- attributeReplaced
Constructor of ServletContextEvent Class
ServletContextEvent contains only one constructor. The web container automatically creates an instance of this class when the ServletContext is initialized during application startup.
Syntax:
ServletContextEvent(ServletContext sc)
Method of ServletContextEvent
ServletContextEvent class has only one method:
ServletContext getServletContext()
This method is used to access the ServletContext instance that is associated with the current event. It helps the listener to get application-level data and perform operations based on context changes.
Syntax:
ServletContext ctx = sce.getServletContext();
Methods of ServletContextListener Interface
Method | Action Performed |
|---|---|
| void contextInitialized(ServletContextEvent e) | Called when application is initialized |
| void contextDestroyed(ServletContextEvent e) | Called when application is destroyed |
Working of Servlet Context Event and Listener
- The client sends a request to the web application.
- The servlet container generates a context-related event (startup/shutdown).
- The registered listener detects the event automatically.
- The listener executes the corresponding method.
- The servlet continues processing normally.
Common Servlet Context Listener Interfaces
| Listener Interface | Description |
|---|---|
| ServletContextListener | Handles application startup and shutdown |
| ServletContextAttributeListener | Handles context attribute changes |
| ServletRequestListener | Handles request lifecycle events |
| HttpSessionListener | Handles session lifecycle events |
How To Configure Context Listener
1. Create Listener Class
Create a class that implements ServletContextListener.
public class MyListenerGfg implements ServletContextListener {
// methods
}
2. Configure Listener in web.xml
In this step, the listener class is registered in web.xml so the container can automatically detect and execute it during application lifecycle events.
<listener>
<listener-class>MyListenerGfg</listener-class>
</listener>
Steps to Implements a ServletContextEvent and ServletContextListener
In this example, we create a page view counter application. The page view count is stored in a database table named counter, and updated using ServletContext and Listener.
Step 1: Create Database Table
First, create a table in MySQL to store page views by executing these query and This table stores total page visits.
CREATE TABLE counter (
pageview INT
);
INSERT INTO counter VALUES (0);

Step 2: Create Dynamic Web Project
- Open Eclipse IDE
- Create a project: ServletFilterchain
- Select: Dynamic Web Project
- Click Finish
Step 3: Create index.html
This HTML page contains a link that calls the servlet when clicked.
<a href="CounterGfg">Total Page views GeeksforGeeks</a>
Step 4: Configure web.xml
The listener is registered to handle application events, and servlet mapping is defined for URL access.

Step 5: Create Listener Class (MyListenerGfg.java)
This class contains a method contextInitialized() which runs when the server starts. It connects to the database and loads the page view count into application memory.
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();
}
}
}
Step 6: Create Servlet (CounterGfg.java)
Retrieves the current page view count from the application (ServletContext).
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);
}
}
Step 7: Run the Project on Server
- Right click project -> Run As -> Run on Server
- Open browser:
http://localhost:8080/ContextListenerGfg/index.html
Output:
On our browser screen the following output will show

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.
