HandlerInterceptor
所有的拦截器必须实现HandlerInterceptor接口,该接口有三个方法,执行顺序如下:
- preHandle(…): Before the actual handler is executed;
- postHandle(…): After the handler is executed;
- afterCompletion(…): After the complete request has finished
注册与配置
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LocaleChangeInterceptor());
registry.addInterceptor(new ThemeChangeInterceptor()).addPathPatterns("/**").excludePathPatterns("/admin/**");
registry.addInterceptor(new SecurityInterceptor()).addPathPatterns("/secure/*");
}
}
多个拦截器执行顺序
执行顺序:按照拦截器的注册顺序依次执行,如果当前拦截器返回false,则后续的拦截器不再执行,直接执行当前拦截器的afterCompletion方法,如下:
boolean applyPreHandle(HttpServletRequest request, HttpServletResponse response) throws Exception {
HandlerInterceptor[] interceptors = getInterceptors();
if (!ObjectUtils.isEmpty(interceptors)) {
for (int i = 0; i < interceptors.length; i++) {
HandlerInterceptor interceptor = interceptors[i];
if (!interceptor.preHandle(request, response, this.handler)) {
triggerAfterCompletion(request, response, null);
return false;
}
this.interceptorIndex = i;
}
}
return true;
}
参考: