recognizing session timeout [duplicate]

心已入冬 提交于 2019-11-29 00:30:21

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);

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!

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