I wrote test.jsp, web.xml and Session listener. For the session timeout, I use the HttpSessionListener function. My session becomes invalid after 1 minute when there is no user interaction with the session. Technology Used: JSP, Servlet JSP
<%@ page import="java.util.List"%> <%@ page import="java.util.ArrayList"%> <html> <head> <title>Servlet Session Listener example</title> </head> <body> <h2>Add User Screen</h2> <span style="float: right"> <a href="DestroySession.jsp">Destroy this session</a> </span> <form method="post" action="AddUser.jsp"> <h3>Enter Username to Add in List</h3> <input type="text" name="user"/> <input type="submit" value="Add User"/> </form> <% List<String> users = (List<String>)session.getAttribute("users"); for(int i=0; null!=users && i < users.size(); i++) { out.println("<br/>" + users.get(i)); } %> </body> </html>
Java code
import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionListener; public class SessionListener implements HttpSessionListener { private int sessionCount = 0; public void sessionCreated(HttpSessionEvent event) { synchronized (this) { sessionCount++; } System.out.println("Session Created: " + event.getSession().getId()); System.out.println("Total Sessions: " + sessionCount); } public void sessionDestroyed(HttpSessionEvent event) { synchronized (this) { sessionCount--; } System.out.println("Session Destroyed: " + event.getSession().getId()); System.out.println("Total Sessions: " + sessionCount); } }
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app> <display-name>SessionListener</display-name> <distributable/> <listener> <listener-class>SessionListener</listener-class> </listener> <session-config> <session-timeout>1</session-timeout> </session-config> </web-app>
My requirement: when there is no user interaction with the session for 1 minute, I want to cancel the session depending on some database value. If the database value is false, then the session should not be invalid. If the database value is true, then the session must be invalid. But after 1 minute (in the absence of user interaction with the session), the sessionDestroyed function of the SessionListener class is automatically called, and I can not check the value of the database. How can i do this?
source share