用法:
继承 HandlerInterceptorAdapter重写相应方法,HandlerInterceptorAdapter中有以下方法:
1)preHandle:预处理方法,在请求处理之间调用,返回true继续后续执行,返回false中断执行,可进行加密、安全控制、校验权限(拦截器中抛出的异常可被全局异常(@RestControllerAdvice)捕获);
2)postHandle:后处理回调方法,在DispatcherServlet处理器返回ModelAndView后,页面渲染前页面渲染执行,
3)afterCompletion:在页面渲染之后执行
4)afterConcurrentHandlingStarted:处理异步请求,Controller中有异步方法的时候会触发该方法
注:如果需要定义多个 HandlerInterceptorAdapter且应用于不同接口,可预先配置,如下
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
@Autowired
private AuthInterceptor authInterceptor;
@Autowired
private SyncInterceptor syncInterceptor;
@Autowired
private AuthSyncInterceptor authSyncInterceptor;
@Autowired
private MdmInterceptor mdmInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(syncInterceptor).addPathPatterns("/api/sync/**", "/api/permission/**");
registry.addInterceptor(authSyncInterceptor).addPathPatterns("/api/auth/sync/**").excludePathPatterns("/api/mdm/**", "/api/permission/**");
registry.addInterceptor(authInterceptor).addPathPatterns("/**").excludePathPatterns("/api/sync/**", "/api/push/**", "/api/auth/sync/**", "/api/mdm/**", "/api/permission/**");
registry.addInterceptor(mdmInterceptor).addPathPatterns("/api/mdm/**");
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/file/**")
.addResourceLocations("file:/app/file/");
}
}