1.拦截器配置
通过WebMvcConfigurer配置拦截器
@Configuration
public class WebMvcConfigurerImpl implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new FirstInterceptor()).addPathPatterns("/hello");
}
}
class FirstInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
return false;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
}
}
访问/hello请求,并进入断点:
(1)进入DispatcherServlet的doDispatch()方法
springboot底层就是使用springmvc的DispatcherServlet类处理请求的
HandlerExecutionChain里面封装的就是当前请求的处理器Object对象和拦截器列表
(2)进入getHandler()
看他如何封装HandlerExecutionChain:
protected HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception {
if (this.handlerMappings != null) {
for (HandlerMapping mapping : this.handlerMappings) {
//HandlerMapping接口用于定义请求和处理程序对象之间的映射
//遍历当前Servlet中的List<HandlerMapping> handlerMappings,寻找合适的HandlerMapping
//当前合适的mapping是RequestMappingHandlerMapping
HandlerExecutionChain handler = mapping.getHandler(request);
if (handler != null) {
return handler;
}
}
}
return null;
}
先看一下HandlerMapping的结构图:
不同的HandlerMapping表示处理不同的映射请求
(3)进入