In Java Servlets, HttpSessionEvent and HttpSessionListener are used to track and handle session lifecycle events such as session creation and destruction in a web application. They help the server automatically detect user session changes and execute custom logic.
- HttpSessionEvent represents session lifecycle events
- HttpSessionListener listens to session creation and destruction
- Used for tracking total and active users in an application
HttpSessionEvent
HttpSessionEvent is an event class in Java Servlet that represents a session-related event such as creation or destruction of an HTTP session. It is passed to HttpSessionListener methods to provide session details.
- Carries information about the current HTTP session
- Used in session lifecycle events (create/destroy)
- Helps listener access session object
Methods of HttpSessionEvent
getSession() : This method returns the HttpSession object associated with the event. It helps to access session details like session ID and attributes.
Syntax:
HttpSession getSession()
HttpSessionListener
HttpSessionListener is an interface in Java Servlet used to listen to HTTP session lifecycle events such as session creation and destruction. It automatically notifies the application whenever a user session starts or ends.
- It tracks session creation and session destruction events
- Used for session monitoring like active users count
- Implemented by a class to handle session lifecycle actions
Methods of HttpSessionListener
There are two methods of the HttpSessionListner interface
1. sessionCreated()
This method is called automatically when a new session is created in a web application. It is used to perform actions like counting new users or initializing session data.
Syntax:
void sessionCreated(HttpSessionEvent se)
2. sessionDestroyed()
This method is called when a session is destroyed or invalidated. It is used to update user count or release session-related resources.
Syntax:
void sessionDestroyed(HttpSessionEvent se)
Steps to Implements HttpSessionEvent and HttpSessionListener
We will create a web application that counts total users and active users using session events.
Step 1: Create index.html
This page takes user input and sends it to the LoginServlet for session creation.
<!DOCTYPE html>
<html>
<body>
<h2>Login Credentials</h2>
<form action="servlet">
Username:<input type="text" name="username"><br>
Password:<input type="password" name="userpass"><br>
<input type="Submit" value="Sign-in"/>
</form>
</body>
</html>
Step 2: Configure web.xml
This file registers the listener and maps login/logout servlets with URLs.
<web-app>
<listener>
<listener-class>CountUserListener</listener-class>
</listener>
<servlet>
<servlet-name>login</servlet-name>
<servlet-class>LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>login</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>logout</servlet-name>
<servlet-class>LogoutServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>logout</servlet-name>
<url-pattern>/logout</url-pattern>
</servlet-mapping>
</web-app>
Step 3: Create Listener (CountUserListener.java)
This listener class counts the total and active sessions and stores this information as an attribute in the ServletContext object.
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
public class CountUserListener implements HttpSessionListener{
ServletContext scx =null;
static int all =0, active =0;
// It receives the notification that
// a session has been created.
public void sessionCreated(HttpSessionEvent se)
{
all++;
active++;
scx =se.getSession().getServletContext();
scx.setAttribute("All Users", all);
scx.setAttribute("Active Users", active);
}
// It receives the notification that
// a session is almost invalidated
public void sessionDestroyed(HttpSessionEvent se)
{
active--;
scx.setAttribute("Active Users", active);
}
}
Step 4: Create LoginServlet.java
This servlet creates a session for the user and displays total and active users from ServletContext.
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class LoginServlet extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html; charset=UTF-8");
PrintWriter out = response.getWriter();
String str = request.getParameter("Username");
out.print("Welcome "+str);
HttpSession session = request.getSession();
session.setAttribute("Uname",str);
// this retrieve data from ServletContext object
ServletContext scx = getServletContext();
int au = (Integer)scx.getAttribute("All Users");
int acu = (Integer)scx.getAttribute("Active Users");
out.print("<br>All Users = "+au);
out.print("<br>Active Users = "+acu);
out.print("<br><a href='logout'>Logout</a>");
out.close();
}
}
Step 5: Create LogoutServlet.java
This servlet destroys the session and triggers sessionDestroyed() method in listener.
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class LogoutServlet extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
HttpSession session=request.getSession(false);
// This invalidates the session
session.invalidate();
out.print("You are successfully logged out");
out.close();
}
}
Step 6: Run your Application
Right click project -> Run As -> Run on Server
Open browser:
http://localhost:8080/SessionCounter/index.html
User opens the login page and enters username and password to start the session tracking process.

First user Alice logs in successfully, and the system creates a session. Total users and active users both become 1.

Second user Bob logs in while the first session is still active. Now total users = 2 and active users = 2.

First user (Alice) logs out, so her session ends. Total users remain 2, but active users reduce to 1.

Now Bob is still logged in, so total users remain 2, and active users stay 1 while his session continues.

Explanation: This program uses HttpSessionListener to automatically track user sessions in the web application. Whenever a user logs in, the sessionCreated() method is triggered, which increases both total and active user counts. When the user logs out and the session is invalidated, the sessionDestroyed() method runs and decreases the active user count.