HTTP Session: how to configure URLs that not change the session expiration?

这一生的挚爱 提交于 2019-11-29 17:08:22

This is not supported by standard Servlet API.

Your best bet is to create a global servlet filter (with @WebFilter("/*")) which decreases the HttpSession#setMaxInactiveInterval() every time when the particular URL hits the server, and puts it back to the default value for other URLs. It only requires a bit of basic math.

The relevant bits of the implementation can look like this:

private static final int DEFAULT_EXPIRE_TIME_IN_SECONDS = 1800;
private static final String SKIP_EXPIRE_TIME_ON_URI = "/somePollServlet";

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

    if (request.getRequestURI().equals(request.getContextPath() + SKIP_EXPIRE_TIME_ON_URI)) {
        long lastAccessedTime = session.getLastAccessedTime();
        long currentTime = System.currentTimeMillis();
        int newExpireTime = DEFAULT_EXPIRE_TIME_IN_SECONDS - (int) ((currentTime - lastAccessedTime) / 1000);
        session.setMaxInactiveInterval(newExpireTime);
    }
    else {
        session.setMaxInactiveInterval(DEFAULT_EXPIRE_TIME);
    }

    chain.doFilter(req, res);
}

There are many approaches to doing this. One of them is to use a javascript for example JQuery . The main idea is regardless of whether a script is polling the server, if there is no activity on the application by the user for example key press, mouse movement etc for a reasonable duration, it needs to be considered that the user is not present and the javascript needs to call the logout url for your applications. Please refer to the provided URL that actually explains the concept very well.

shazin

In your case you need a Session management scheme that will expire in N minutes time regardless of whether the user stays active or not. That way you don't need to by pass any authentication or default cookies.

You can achieve it by using two methods proposed here.

  1. A Scheduled Job which invalidates the session after N minutes from login
  2. An Header and Filter based approach to decide the session expiration dynamically.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!