我已经编写了一个 test.jsp、web.xml 和会话监听器。对于会话超时,我正在使用功能。我HttpSessionListener
的会话在 1 分钟后失效,当时没有用户与会话交互。使用技术: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 代码
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>
我的要求是:当用户与会话没有交互 1 分钟时,我想根据某些数据库值使会话无效。如果数据库值为 false,则不应使会话无效。如果数据库值为真,则会话应无效。但是 1 分钟后(当用户与会话没有交互时),SessionListener 类的 sessionDestroyed 函数被自动调用,我无法检查数据库值。我怎样才能做到这一点?