Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
457 views
in Technique[技术] by (71.8m points)

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

I have in my application polling HTTP requests that executed each 5 minutes.

I want to configure those URLs not to change the session expiration. Otherwise my session will never expired (and I do not want it). Was not able to find it in the web.xml and HttpSession documentation.

How is possible to do it?

Added

Very important clarification: the request should be authenticated. It means that the request should be attached to JsessionID that is already authenticated.

Clarification (Added 2)

I do not want the session will expire regardless of whether the user stays active or not. I want the session will expire on the user inactivity and will not be expire if user working on UI. I want the session will expire on the user inactivity in spite of polling requests that come each 5 minutes

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...