我正在使用servlet构建一个Java网络棋盘游戏。 我需要知道当用户30秒没有响应时,我要使用
session.setMaxInactiveInterval(30);
但是我需要在服务器端知道时间结束后,以便让这个玩家退出。
现在当玩家返回并尝试做某事时,他会遇到超时,我可以在服务器上看到。
我该如何在servlet中知道会话何时超时?!
谢谢。
我正在使用servlet构建一个Java网络棋盘游戏。 我需要知道当用户30秒没有响应时,我要使用
session.setMaxInactiveInterval(30);
但是我需要在服务器端知道时间结束后,以便让这个玩家退出。
现在当玩家返回并尝试做某事时,他会遇到超时,我可以在服务器上看到。
我该如何在servlet中知道会话何时超时?!
谢谢。
您需要实现HttpSessionListener
接口。当会话创建或销毁时,它会收到通知事件。特别是在会话被销毁之后,即超时期结束/会话失效之后,它的方法sessionDestroyed(HttpSessionEvent se)
会被调用。您可以通过HttpSessionEvent#getSession()
调用获取存储在会话中的信息,并随后对会话进行必要的任何安排。此外,请确保在web.xml
中注册您的会话侦听器:
<listener>
<listener-class>FQN of your sessin listener implementation</listener-class>
</listener>
long now = new java.util.Date().getTime();
boolean timeout = (now - session.getLastAccessedTime()) >= ((long)session.getMaxInactiveInterval() * 1000L);
httpServletRequest.getSession().setAttribute("logout", true);
// invalidate the principal
httpServletRequest.logout();
// invalidate the session
httpServletRequest.getSession().invalidate();
@Override
public void sessionDestroyed(HttpSessionEvent event) {
HttpSession session = event.getSession();
if (session.getAttribute("logout") == null) {
// it's a timeout
}
}
ServletContext servletContext=se.getSession().getServletContext();
谢谢!