SpringBoot攔截器

首先我們要先創(chuàng)建一個攔截器。先附上代碼:

@Component
public class LoginHandlerInterceptor implements HandlerInterceptor {

    //目標(biāo)方法執(zhí)行之前
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Object user = request.getSession().getAttribute("currentUser");
        if (user == null) {
            //未登錄,返回登錄頁面
            response.sendRedirect("/LoginError.html");
            return false;
        }else {
            //放行
            return true;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {

    }
}

?先創(chuàng)建一個HandlerInterceptor類并實(shí)現(xiàn)org.springframework.web.servlet.HandlerInterceptor這個接口中的三個方法,通過方法名就可以看出三個方法分別可在要攔截的請求執(zhí)行之前、中,后進(jìn)行相關(guān)的處理。本例是對攔截url進(jìn)行是否已經(jīng)登錄的攔截驗(yàn)證。注意還有一個@Component注解不要忘記了。
?攔截時的處理方式很簡單,攔截時判斷用戶是否已經(jīng)登錄,如果登錄了就放行,否則跳轉(zhuǎn)回指定頁面。

然后創(chuàng)建一個Config來注冊攔截器,代碼如下:

@Configuration
public class MyMvcConfig implements WebMvcConfigurer {

    //所有的WebMvcConfigurerAdapter組件都會一起起作用
    @Bean //將組件注冊在容器中
    public WebMvcConfigurer webMvcConfigurerAdapter(){
        return new WebMvcConfigurer(){

            //注冊攔截器
            @Override
            public void addInterceptors(InterceptorRegistry registry) {
                //靜態(tài)資源; *.css,*.js
                //SpringBoot已經(jīng)做好了靜態(tài)資源映射
//                registry.addInterceptor(new LoginHandlerInterceptor()).addPathPatterns("/**")
//                .excludePathPatterns("/index.html","/","/user/login","/static/**","/webjars/**");
                // /**  表示攔截所有路徑下的所有請求
                registry.addInterceptor(new LoginHandlerInterceptor())
                        .addPathPatterns("/person.html","/Person.html",
                                "/questionnaire.html","/Questionnaire.html",
                                "/result.html","/Result.html");
            }
        };
    }

}

?@Configuration,@Bean注解,org.springframework.web.servlet.config.annotation.WebMvcConfigurer接口。
?其中addInterceptor方法用于把剛才創(chuàng)建的攔截器加入到registry中,addPathPatterns用戶加入所要攔截的url,/**表示攔截所有請求。excludePathPatterns添加不需要攔截的請求。
?至此,一個攔截器就配置好了。如果需要配置多個攔截,只需要另外創(chuàng)建一個攔截器,給registry再加一個inteceptor就可以了,不用再創(chuàng)建一個新的config配置類。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容