识别会话超时



我正在使用servlet构建一个java web棋盘游戏。我需要知道当用户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);

我最终使用httpessionlistener和刷新的间隔大于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();

则可以在httpessionlistener类中包含以下内容:

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

最新更新