在spring應用中註冊interceptor思路

基本接口:WebMvcConfigurer或者WebMvcConfigurerAdapter;

函數:addInterceptors(InterceptorRegistry registry);

參數類型說明:InterceptorRegistry類只包含List<InterceptorRegistration>列表一個成員字段;InterceptorRegistration類封裝了

Interceptor對象、includeUrl和excludeUrls;

(1)向系統註冊一個攔截器

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new MyCustomInterceptor());
    }
}

(2)實現一個攔截器,攔截器實現HandlerInterceptor接口

public class MyCustomInterceptor implements HandlerInterceptor{

    @Override
    public boolean preHandle(HttpServletRequest request,HttpServletResponse  response){
    //your custom logic here.
        return true;
    }
}

(3)針對某些url進行攔截

 InterceptorRegistration.addPathPatterns()和InterceptorRegistration.excludePathPatterns()函數實現

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章