1. 程式人生 > >spring boot (十七)攔截器定義

spring boot (十七)攔截器定義

1、攔截器配置

@Configuration
public class WebMvcConfigurer extends WebMvcConfigurerAdapter {
    @Autowried
    private AuthInterceptor authInterceptor;
    @Autowried
    private HttpInterceptor httpInterceptor;
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        /**
         * 攔截器按照順序執行
         */
        registry.addInterceptor(httpInterceptor);
        registry.addInterceptor(authInterceptor).addPathPatterns("/**").excludePathPatterns("/login"); 
        super.addInterceptors(registry);
    }
 
}

2.定義攔截器

public class AuthInterceptor  implements HandlerInterceptor {
    /**
     * 在整個請求結束之後被呼叫,也就是在DispatcherServlet 渲染了對應的檢視之後執行
     * (主要是用於進行資源清理工作)
     */
    @Override
    public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
            throws Exception {
        //after
 
    }
 
    /**
     * 請求處理之後進行呼叫,但是在檢視被渲染之前(Controller方法呼叫之後)
     */
    @Override
    public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
            throws Exception {
        //post
 
    }
    /**
     * 在請求處理之前進行呼叫(Controller方法呼叫之前)
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws Exception {
        //一般可以進行許可權驗證request.getSession
        return true; //放行
    } 
}