HTTP 会话:如何配置不改变会话过期时间的 URL? [英] HTTP Session: how to configure URLs that not change the session expiration?

查看:28
本文介绍了HTTP 会话:如何配置不改变会话过期时间的 URL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序轮询 HTTP 请求,每 5 分钟执行一次.

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

我想将这些 URL 配置为不更改会话过期时间.否则我的会话将永远不会过期(我不想要它).无法在 web.xml 和 HttpSession 文档中找到它.

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.

怎么可能做到?

已添加

非常重要的说明:应该对请求进行身份验证.这意味着该请求应该附加到已经通过身份验证的 JsessionID.

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

说明(添加 2 个)

我不希望无论用户是否保持活动状态,会话都会过期.我希望会话将在用户不活动时过期,并且在用户使用 UI 时不会过期.尽管每 5 分钟有轮询请求,但我希望会话在用户不活动时过期

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

推荐答案

标准 Servlet API 不支持.

This is not supported by standard Servlet API.

您最好的办法是创建一个全局 servlet 过滤器(使用 @WebFilter("/*")),以减少 HttpSession#setMaxInactiveInterval() 每次当特定的 URL 到达服务器,并将其恢复为其他 URL 的默认值.它只需要一点基础数学.

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

这篇关于HTTP 会话:如何配置不改变会话过期时间的 URL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆