Servlet - HttpSessionEvent and HttpSessionListener
Last Updated :
30 Jan, 2022
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, accept these notification events, the implementation of the class must follow one of the following:
- It should be declared in the deployment descriptor of the web application, annotated with WebListener
- It should be registered via one of the addListener methods defined on ServletContext
There are two methods of the HttpSessionListner interface:
- sessionCreated: It receives the notification that a session has been created.
- sessionDestroyed: It receives the notification that a session is almost invalidated.
// Parameter: se - the HttpSessionEvent containing the session
void sessionCreated(HttpSessionEvent se)
// Parameter: se - the HttpSessionEvent containing the session
void sessionDestroyed(ServletContextEvent se)
Example
Count the total and the active sessions, using HttpSessionEvent and HttpSessionListener. Now, we have to create these files:
- index.html
- CountUserListner.java
- LoginServlet.java
- LogoutServlet.java
index.html: Login Credentials
HTML
<!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>
CountUserListner.java: This listener class counts the total and active sessions and stores this information as an attribute in the ServletContext object.
Java
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);
}
}
LoginServlet.java: This Servlet class creates a session and prints the total and current active users.
Java
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();
}
}
LogoutServlet.java: This Servlet class invalidates session.
Java
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();
}
}
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 - Context Event and Context Listener 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 ServletContextListe
3 min read
Servlet - HttpSession Login and Logout Example In general, the term "Session" in computing language, refers to a period of time in which a user's activity happens on a website. Whenever you login to an application or a website, the server should validate/identify the user and track the user interactions across the application. To achieve this, J
8 min read
The HttpSession Interface in Servlet What is a session? In web terminology, a session is simply the limited interval of time in which two systems communicate with each other. The two systems can share a client-server or a peer-to-peer relationship. However, in Http protocol, the state of the communication is not maintained. Hence, the
4 min read
Servlet - Authentication Filter Servlets are the Java programs that run on the Java-enabled web server or application server. They are used to handle the request obtained from the webserver, process the request, produce the response, then send a response back to the webserver. Authentication Filter In Servlets Authentication may
2 min read