【问题标题】:Can a session expire while being processed during doPost / doGet, if so what action can be taken在 doPost / doGet 期间处理会话时是否会过期,如果是,可以采取什么操作
【发布时间】:2015-02-16 03:05:38
【问题描述】:

目前我使用以下过滤器在会话过期后将用户重定向到索引页面。

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest)request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        HttpSession httpSession = httpRequest.getSession(false);
        if (httpSession != null && !httpSession.isNew()) {
            chain.doFilter(request, response);
        } else {
            httpResponse.sendRedirect(request.getServletContext().getContextPath() + PathManager.getPagePath("index"));
        }
    }

但是在 doPost/doGet 方法中执行代码时会话会过期吗?所以在进入过滤器时会话是好的,但是会话在 servlet 的 doPost/doGet 方法中过期。

如果出现这种情况,有什么办法可以将用户重定向到登录页面?

【问题讨论】:

标签: java session servlets servlet-filters session-timeout


【解决方案1】:

您可以在会话过期时向客户端抛出异常/消息,然后让客户端将用户重定向到登录页面。

要检测会话是否已过期,您需要从 ServletRequest 中获取会话,如果它为 null,则它已过期。

//false parameter is used to return the existing session. if expired then null is returned.
final HttpSession session  = request.getSession(false);

【讨论】:

  • 问题是我检测不到会话超时。当然,我可以实现一个 SessionListener 并抛出某种 RuntimeException,但它看起来像一个解决方法
  • 不需要 SessionListener。会话过滤器足以解决此问题。注意有你的会话过滤器,过滤所有传入服务器的请求。您可能希望省略登录页面,因为此时用户将没有有效的会话。
猜你喜欢
  • 1970-01-01
  • 2012-11-30
  • 2013-05-25
  • 2023-04-07
  • 1970-01-01
  • 1970-01-01
  • 2016-05-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多