Springboot配置攔截器進行登錄攔截時出現了“重定向的次數過多”,原因是攔截器配置全路徑,無登錄用戶狀態下一直被攔截,導致出現了死循環。
MyInterceptor :
@Component public class MyInterceptor implements HandlerInterceptor { public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { HttpSession session = request.getSession(); if (session.getAttribute("userName") == null) { response.sendRedirect("/login.html"); return false; } else { System.out.println("登錄用戶: " + session.getAttribute("userName")); return true; } } public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { System.out.println("postHandle method is running!"); } public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { System.out.println("afterCompletion method is running!"); } }
MVCConfiguration :
@Configuration public class MVCConfiguration implements WebMvcConfigurer{ @Autowired private MyInterceptor myInterceptor; /** * 重寫接口中的addInterceptors方法,添加自定義攔截器 * @param registry */ public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(myInterceptor).addPathPatterns("/**"); } }
因為配置攔截的是全路徑:"/**",所以當“MyInterceptor”判斷“session.getAttribute("userName") == null”時重定向到“/login.html”時也會被“MVCConfiguration”攔截,所以又跳轉回“MyInterceptor”,導致出現了死循環。
然后就頁面報錯如下圖(轉發也是類似道理,也是死循環):
解決辦法:增添被排除的路徑,對“MVCConfiguration”的攔截路徑進行修改。
修改后的MVCConfiguration:
@Configuration public class MVCConfiguration implements WebMvcConfigurer { @Autowired private MyInterceptor myInterceptor; /** * 重寫接口中的addInterceptors方法,添加自定義攔截器 * * @param registry */ public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(myInterceptor).addPathPatterns("/**").excludePathPatterns("/login.html"); } }