识别会话超时

我正在使用servlet构建一个java web棋盘游戏。 我需要知道用户何时没有回答30秒,我正在使用

session.setMaxInactiveInterval(30); 

但是,一旦时间结束,我需要在服务器端知道,所以我可以使这个播放器相当。

因为现在一旦玩家返回并尝试做某事他将得到超时,我可以在服务器上看到。

一旦会话超时,我怎么能在servlet中知道?!

谢谢。

您需要实现HttpSessionListener接口。 它在创建或销毁会话时接收通知事件。 特别是,它的方法sessionDestroyed(HttpSessionEvent se)在会话被销毁时被调用,这在超时期限结束/会话失效后发生。 您可以通过HttpSessionEvent#getSession()调用获取存储在会话中的信息,然后执行会话所需的任何安排。 另外,请务必在web.xml注册会话侦听器:

  FQN of your sessin listener implementation  

如果您最终想要区分失效和会话超时,可以在侦听器中使用以下行:

 long now = new java.util.Date().getTime(); boolean timeout = (now - session.getLastAccessedTime()) >= ((long)session.getMaxInactiveInterval() * 1000L); 

我最终使用HttpSessionListener并在比setMaxInactiveInterval更大的区间内刷新。

因此,如果在40秒之后的下一次刷新中使用了30秒没有做任何事情,我会进入sessionDestroyed()。

同样重要的是,您需要创建新的ServletContext以获取ServletContext。

 ServletContext servletContext=se.getSession().getServletContext(); 

谢谢!

基于空闲间隔进行猜测的替代方法是在用户触发注销时在会话中设置属性。 例如,如果您可以在处理用户触发的注销的方法中添加以下内容:

 httpServletRequest.getSession().setAttribute("logout", true); // invalidate the principal httpServletRequest.logout(); // invalidate the session httpServletRequest.getSession().invalidate(); 

那么你可以在你的HttpSessionListener类中拥有以下内容:

 @Override public void sessionDestroyed(HttpSessionEvent event) { HttpSession session = event.getSession(); if (session.getAttribute("logout") == null) { // it's a timeout } }