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表示处理不同的映射请求

本文深入探讨了SpringBoot中拦截器的配置过程。首先从手动配置拦截器开始,详细解释了从DispatcherServlet的doDispatch()方法到getHandlerExecutionChain()方法的执行流程,展示了拦截器如何与处理器方法关联。接着,文章分析了拦截器自动配置的原理,重点关注了WebMvcAutoConfiguration和DispatcherServletAutoConfiguration这两个配置类的作用,特别是如何将自定义拦截器封装到MappedInterceptor中,并通过DelegatingWebMvcConfiguration和WebMvcConfigurationSupport的相关方法实现自动配置。
最低0.47元/天 解锁文章
2090

被折叠的 条评论
为什么被折叠?



