recognizing session timeout [duplicate]

北城余情 提交于 2019-12-18 03:01:10

问题


I am building a java web board game using servlets. I need to know when a user is not answering for 30 secundes, I am using

session.setMaxInactiveInterval(30);

But I need to know on the server side once the time ended so I can make this player quite.

As it is now once the player return and try to do something he will get the timeout and I can see on on the server.

How can I know in the servlet once a session has timeout?!

Thank you.


回答1:


You need to implement the HttpSessionListener interface. It receives notification events when session is created, or destroyed. In particular, its method sessionDestroyed(HttpSessionEvent se) gets called when the session is destroyed, which happens after timeout period has finished / session was invalidated. You can get the information stored in the session via HttpSessionEvent#getSession() call, and later do any arrangements that are necessary with the session. Also, be sure to register your session listener in web.xml:

<listener>
    <listener-class>FQN of your sessin listener implementation</listener-class>
</listener>

If you ultimately want to distinguish between invalidation and session timeout you could use the following line in your listener:

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



回答2:


I ended up using the HttpSessionListener and refreshing in an interval larger then setMaxInactiveInterval.

So if the used did nothing for 30 Sec in the next refresh after 40 Sec I get to sessionDestroyed().

Also important that you need to create new ServletContext to get to the ServletContext.

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

Thank you!




回答3:


An alternative to guessing based on the idle interval is to set an attribute in the session when the logout is triggered by the user. For example, if you can put something like the following in the method that handles user triggered logouts:

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

then you can have the following in your HttpSessionListener class:

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


来源:https://stackoverflow.com/questions/15223841/recognizing-session-timeout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!