首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Java过滤器无限循环

Java过滤器无限循环
EN

Stack Overflow用户
提问于 2012-10-29 09:05:34
回答 2查看 7.8K关注 0票数 3

我想实现一个过滤器来进行身份验证,但不知何故它陷入了无限循环……任何想法都很感谢。

代码语言:javascript
运行
复制
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;

    doBeforeProcessing(request, response);

    Throwable problem = null;
    HttpSession session = httpRequest.getSession(true);
    if(session.getAttribute("userName")!=null&&session.getAttribute("userName")!=(""))
    {
        try {
            chain.doFilter(request, response);
        } catch (Throwable t) {
            // If an exception is thrown somewhere down the filter chain,
            // we still want to execute our after processing, and then
            // rethrow the problem after that.
            problem = t;
            t.printStackTrace();
        }   
    }else{
        httpResponse.sendRedirect("login.jsp");
        return;
    }

这段代码在调试模式下运行了无限次,基本上我想在用户未登录时将其重定向到login.jsp。任何回答都很感谢。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-10-29 09:22:39

这里,

代码语言:javascript
运行
复制
httpResponse.sendRedirect("login.jsp");

您将为目标页面发送一个新的HTTP请求,而不是使用当前的请求。如果这个新的超文本传输协议请求被映射到一个过于通用的URL模式,比如/*,那么它当然会再次命中过滤器。并且将执行相同的检查并且它将再次被重定向。等等。这是一个永无止境的故事。

当当前请求的页面是登录页面时,还需要添加额外的检查来执行FilterChain#doFilter()

代码语言:javascript
运行
复制
String loginURL = httpRequest.getContextPath() + "/login.jsp";

if (httpRequest.getRequestURI().equals(loginURL)) || session.getAttribute("userName") != null) {
    chain.doFilter(request, response);
} else {
    httpResponse.sendRedirect(loginURL);
}

注意,我还删除了对作为username的空字符串的无意义的检查(但是,您需要确保您的代码没有将空字符串设置为username。只需使用null表示未登录的用户即可。还请注意,我还修复了重定向URL,因为当当前请求的URL在子文件夹中时,它将失败。

一种不同的选择是将所有这些受限制的页面放在一个公共的子文件夹中,例如/app/secured/restricted等,然后将过滤器映射到/app/*/secured/*/restricted/*等的URL模式。如果您将登录页面放在此文件夹之外,则在请求登录页面时不会调用筛选器。

票数 10
EN

Stack Overflow用户

发布于 2012-10-29 09:23:21

问题是您的筛选器是在login.jsp上运行的,当用户未登录时,将反复重定向到它自己。由于filter url-pattern上没有排除语法,因此如果您已经在login.jsp页面上,则需要检测过滤器中的URL并省略重定向:

代码语言:javascript
运行
复制
    // your auth code
} else {
    String redirect = httpRequest.getContextPath() + "/login.jsp";
    String uri = httpRequest.getRequestURI().toString();
    if (uri.endsWith(redirect)){
        // URI ends with login.jsp, just process the chain
        chain.doFilter();
    } else {
        // not on the login page and not logged in, redirect
        httpResponse.sendRedirect(redirect);
        return;
    }
}
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13114743

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档