java - 在 doPost/doGet 期间处理 session 时 session 是否会过期,如果是,可以采取什么操作

标签 java session servlets servlet-filters session-timeout

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

    @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 方法中执行代码时, session 会过期吗?因此,在进入过滤器时, session 正常,但 session 在 servlet 的 doPost/doGet 方法内过期。

如果发生这种情况,将用户重定向到登录页面的解决方案是什么?

最佳答案

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

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

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

关于java - 在 doPost/doGet 期间处理 session 时 session 是否会过期,如果是,可以采取什么操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27527751/

相关文章:

php - 使用 ajax 和 php 时的用户身份验证和重定向

c# - 将 session 转换为 int 以进行 linq 查询

java - 从 Java 应用程序调用 Servlet 时出现服务器错误

java - 无法识别的属性名称 MODULE(com.sun.tools.javac.util.SharedNameTable$NameImpl 类)

java - 无法实例化 Kafka 结构化流 KafkaSourceProvider

java - ksoap2-android信封的定制

java - 可以存储在 HashMap 中的键(对象)数量的理论限制?

python - 在 django.test.client 中保留 session ID

java - 使用jsp页面导入时Cannot Find Symbol错误

java - 服务程序 : Image upload with content type as image/jpeg