基本接口: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()函數實現