Springboot配置攔截器無法跳轉登錄頁面


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");
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM