Programmatically change session timeout

2019-04-12 21:28发布

I can logout user after defined time of inactivity.

<session-timeout>240</session-timeout> 

But, is there some way to logout in specified time, or better, for example until 5 minutes of inactivity after specified time.?

3条回答
放我归山
2楼-- · 2019-04-12 21:29

What Bozho has given you is correct, what you are seeing most likely is that when you press your logout button, the session is being destroyed, but the servlet container is then being directed to a "post logout" page, which automatically causes a session to be created (Hence "Session Destroyed" followed by "Session Created").

Short of creating your own session handling system, I don't know how you would get around this. (I've had this issue in the past and it disappeared after we created our own session system)

查看更多
Emotional °昔
3楼-- · 2019-04-12 21:34

You can change the session timeout by HttpSession#setMaxInactiveInterval() wherein you can specify the desired timeout in seconds.

When you want to cover a broad range of requests for this, e.g. all pages in folder /admin or something, then the best place to do this is to create a Filter which is mapped on the FacesServlet which does roughly the following job:

@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws ServletException, IOException {
    HttpServletRequest request = (HttpServletRequest) req;
    HttpSession session = request.getSession();

    if (request.getRequestURI().startsWith("/admin/")) {
        session.setMaxInactiveInterval(60 * 5); // 5 minutes.
    } else {
        session.setMaxInactiveInterval(60 * 240); // 240 minutes.
    }

    chain.doFilter(req, res);
}

In a JSF managed bean the session is available by ExternalContext#getSession():

HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession();
// ...

Or when you're already on JSF 2.1, then you can also use the new ExternalContext#setSessionMaxInactiveInterval() which delegates to exactly that method.

查看更多
疯言疯语
4楼-- · 2019-04-12 21:41

Automatically - no.

You'd have to:

  • store all sessions in a Set. Do this in a HttpSessionListener when they are created.
  • at the given time (using quartz for example) .invalidate() them
查看更多
登录 后发表回答