说明:当使用拦截器出现“请求转发”无限循环或者“重定向”次数过多这种问题的时候,一般都是 拦截器 设置错了

情况一:请求转发时没有配置排除拦截路径,就是说你访问的路径都拦截了,导致一直转发,从而产生java.lang.StackOverflowError错误

情况二:重定向时没有配置排除拦截路径,会导致一直重定向/重定向次数过多

解决办法:正确添加拦截路径,正确排除拦截路径

Spring Boot中我因疏忽导致的错误(参考):

错误写法:
@Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoginHandlerInterceptor())
                // addPathPatterns 用于添加拦截规则
                // excludePathPatterns 用于排除拦截
                //注:因为疏忽下方的index.html前面未加/,转发多次-->StackOverflowError
                .addPathPatterns("/**").excludePathPatterns("index.html","/","/login","/user/login",
                "/assets/**","/assets/brand/**","/assets/dist/css/**","/assets/dist/js/**");
    }
正确写法:

自定义的实现了WebMvcConfigurer接口的配置类,并重写addInterceptors方法

@Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoginHandlerInterceptor())
                // addPathPatterns 用于添加拦截规则
                // excludePathPatterns 用于排除拦截
                .addPathPatterns("/**").excludePathPatterns("/index.html","/","/login","/user/login",
                "/assets/**","/assets/brand/**","/assets/dist/css/**","/assets/dist/js/**");
    }
拦截器:
public class LoginHandlerInterceptor  implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //登陆成功之后,获取用户的session
        Object loginUser = request.getSession().getAttribute("loginUser");
        if (loginUser==null){//未登录
            System.out.println(request.getRequestURI());
            request.getRequestDispatcher("index.html").forward(request,response);
            // response.sendRedirect("index.html");
            return false;
        }else {
            return true;
        }
    }
}
教训:写代码要细心