当前位置:   article > 正文

Spring MVC 源码 - HandlerAdapter 组件(一)之 HandlerAdapter_handler组件

handler组件

HandlerAdapter 组件

HandlerAdapter 组件,处理器的适配器。因为处理器 handler 的类型是 Object 类型,需要有一个调用者来实现 handler 是怎么被执行。Spring 中的处理器的实现多变,比如用户的处理器可以实现 Controller 接口或者 HttpRequestHandler 接口,也可以用 @RequestMapping 注解将方法作为一个处理器等,这就导致 Spring MVC 无法直接执行这个处理器。所以这里需要一个处理器适配器,由它去执行处理器

HandlerAdapter 组件(一)之 HandlerAdapter

先来回顾一下在 DispatcherServlet 中处理请求的过程中哪里使用到 HandlerAdapter 组件,可以回到《一个请求响应的旅行过程》中的 DispatcherServletdoDispatch 方法中看看,如下:

  1. protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
  2. HttpServletRequest processedRequest = request;
  3. HandlerExecutionChain mappedHandler = null;
  4. ModelAndView mv = null;
  5. // ... 省略相关代码
  6. // <3> 获得请求对应的 HandlerExecutionChain 对象(HandlerMethod 和 HandlerInterceptor 拦截器们)
  7. mappedHandler = getHandler(processedRequest);
  8. // ... 省略相关代码
  9. // <4> 获得当前 handler 对应的 HandlerAdapter 对象
  10. HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler());
  11. // ... 省略相关代码
  12. // <6> 真正的调用 handler 方法,也就是执行对应的方法,并返回视图
  13. mv = ha.handle(processedRequest, response, mappedHandler.getHandler());
  14. // ... 省略相关代码
  15. }
  16. protected HandlerAdapter getHandlerAdapter(Object handler) throws ServletException {
  17. if (this.handlerAdapters != null) {
  18. for (HandlerAdapter adapter : this.handlerAdapters) {
  19. if (adapter.supports(handler)) {
  20. return adapter;
  21. }
  22. }
  23. }
  24. throw new ServletException("No adapter for handler [...");
  25. }

通过遍历 HandlerAdapter 组件们,判断是否支持处理该 handler 处理器,支持则返回该 HandlerAdapter 组件。注意,这里是通过一个一个的 HandlerAdapter 组件去判断是否支持该处理器,如果支持则直接返回这个 HandlerAdapter 组件,不会继续下去,所以获取处理器对应 HandlerAdapter 组件是有一定的先后顺序的,默认是HttpRequestHandlerAdapter -> SimpleControllerHandlerAdapter -> RequestMappingHandlerAdapter

本文涉及到的内容适中,可以先查看我的总结

HandlerAdapter 接口

org.springframework.web.servlet.HandlerAdapter接口,处理器的适配器,去执行处理器,代码如下:

  1. public interface HandlerAdapter {
  2. /**
  3. * 是否支持该处理器
  4. */
  5. boolean supports(Object handler);
  6. /**
  7. * 执行处理器,返回 ModelAndView 结果
  8. */
  9. @Nullable
  10. ModelAndView handle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception;
  11. /**
  12. * 返回请求的最新更新时间,如果不支持该操作,则返回 -1 即可
  13. */
  14. long getLastModified(HttpServletRequest request, Object handler);
  15. }

HandlerAdapter 接口的体系结构如下:

没有特别多 心里有点点欣慰,其中 RequestMappingHandlerAdapter 就是基于@RequestMapping 等注解的 HandlerMethod 的 HandlerMethodAdapter 实现类,名字都差不多

初始化过程

DispatcherServletinitHandlerAdapters(ApplicationContext context) 方法,会在 onRefresh 方法被调用,初始化 HandlerAdapter 组件,方法如下:

  1. private void initHandlerAdapters(ApplicationContext context) {
  2. this.handlerAdapters = null;
  3. if (this.detectAllHandlerAdapters) {
  4. // Find all HandlerAdapters in the ApplicationContext, including ancestor contexts.
  5. Map<String, HandlerAdapter> matchingBeans =
  6. BeanFactoryUtils.beansOfTypeIncludingAncestors(context, HandlerAdapter.class, true, false);
  7. if (!matchingBeans.isEmpty()) {
  8. this.handlerAdapters = new ArrayList<>(matchingBeans.values());
  9. // We keep HandlerAdapters in sorted order.
  10. AnnotationAwareOrderComparator.sort(this.handlerAdapters);
  11. }
  12. }
  13. else {
  14. try {
  15. HandlerAdapter ha = context.getBean(HANDLER_ADAPTER_BEAN_NAME, HandlerAdapter.class);
  16. this.handlerAdapters = Collections.singletonList(ha);
  17. }
  18. catch (NoSuchBeanDefinitionException ex) {
  19. // Ignore, we'll add a default HandlerAdapter later.
  20. }
  21. }
  22. // Ensure we have at least some HandlerAdapters, by registering
  23. // default HandlerAdapters if no other adapters are found.
  24. /**
  25. * 如果未获得到,则获得默认配置的 HandlerAdapter 类
  26. * {@link org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter}
  27. * {@link org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter}
  28. * {@link org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter}
  29. */
  30. if (this.handlerAdapters == null) {
  31. this.handlerAdapters = getDefaultStrategies(context, HandlerAdapter.class);
  32. if (logger.isTraceEnabled()) {
  33. logger.trace("No HandlerAdapters declared for servlet '" + getServletName() +
  34. "': using default strategies from DispatcherServlet.properties");
  35. }
  36. }
  37. }
  1. 如果“开启”探测功能,则扫描已注册的 HandlerAdapter 的 Bean 们,添加到 handlerAdapters 中,默认开启,这里会进行排序,可以通过实现 Order 接口设置排序值

  1. 如果“关闭”探测功能,则获得 Bean 名称为 "handlerAdapter" 对应的 Bean ,将其添加至 handlerAdapters

  1. 如果未获得到,则获得默认配置的 HandlerAdapter 类,调用

getDefaultStrategies(ApplicationContext context, Class<T> strategyInterface) 方法,就是从 DispatcherServlet.properties 文件中读取 HandlerAdapter 的默认实现类,如下:

  1. org.springframework.web.servlet.HandlerAdapter=org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter,\
  2. org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter,\
  3. org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter

可以看到对应的是 HttpRequestHandlerAdapter、SimpleControllerHandlerAdapter、RequestMappingHandlerAdapter 三个实现类,接下来就一个一个分析

HttpRequestHandlerAdapter

org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter,实现 HandlerAdapter 接口,基于 HttpRequestHandler 接口的 HandlerAdapter 实现类,代码如下:

  1. public class HttpRequestHandlerAdapter implements HandlerAdapter {
  2. @Override
  3. public boolean supports(Object handler) {
  4. // 判断是 HttpRequestHandler 类型
  5. return (handler instanceof HttpRequestHandler);
  6. }
  7. @Override
  8. @Nullable
  9. public ModelAndView handle(HttpServletRequest request, HttpServletResponse response, Object handler)
  10. throws Exception {
  11. // HttpRequestHandler 类型的调用
  12. ((HttpRequestHandler) handler).handleRequest(request, response);
  13. return null;
  14. }
  15. @Override
  16. public long getLastModified(HttpServletRequest request, Object handler) {
  17. // 处理器实现了 LastModified 接口的情况下
  18. if (handler instanceof LastModified) {
  19. return ((LastModified) handler).getLastModified(request);
  20. }
  21. return -1L;
  22. }
  23. }
  24. // org.springframework.web.HttpRequestHandler.java
  25. @FunctionalInterface
  26. public interface HttpRequestHandler {
  27. /**
  28. * 处理请求
  29. */
  30. void handleRequest(HttpServletRequest request, HttpServletResponse response)
  31. throws ServletException, IOException;
  32. }

逻辑比较简单,如果这个处理器实现了 HttpRequestHandler 接口,则使用 HttpRequestHandlerAdapter 调用该处理器的 handleRequest(HttpServletRequest request, HttpServletResponse response)方法去处理器请求,返回 null

这种处理器如何配置呢?

可以回到《HandlerMapping 组件(四)之 AbstractUrlHandlerMapping》SimpleUrlHandlerMapping 或者 BeanNameUrlHandlerMapping 小节中的使用示例看看


SimpleControllerHandlerAdapter

org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter,实现 HandlerAdapter 接口,基于 Controller 接口的 HandlerAdapter 实现类,代码如下:

  1. public class SimpleControllerHandlerAdapter implements HandlerAdapter {
  2. @Override
  3. public boolean supports(Object handler) {
  4. // <1> 判断是 Controller 类型
  5. return (handler instanceof Controller);
  6. }
  7. @Override
  8. @Nullable
  9. public ModelAndView handle(HttpServletRequest request, HttpServletResponse response, Object handler)
  10. throws Exception {
  11. // <2> Controller 类型的调用
  12. return ((Controller) handler).handleRequest(request, response);
  13. }
  14. @Override
  15. public long getLastModified(HttpServletRequest request, Object handler) {
  16. // 处理器实现了 LastModified 接口的情况下
  17. if (handler instanceof LastModified) {
  18. return ((LastModified) handler).getLastModified(request);
  19. }
  20. return -1L;
  21. }
  22. }
  23. @FunctionalInterface
  24. public interface Controller {
  25. /**
  26. * 处理请求
  27. */
  28. @Nullable
  29. ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception;
  30. }

逻辑比较简单,和 HttpRequestHandlerAdapter 差不多,如果这个处理器实现了 Controoler 接口,则使用 HttpRequestHandlerAdapter 调用该处理器的 handleRequest(HttpServletRequest request, HttpServletResponse response)方法去处理器请求,直接返回处理器执行后返回 ModelAndView

这种处理器如何配置和 HttpRequestHandlerAdapter 相同,见上文描述

SimpleServletHandlerAdapter 实现类就不讲述了,因为默认的 HandlerAdapter 实现类中没有它
逻辑实现和 SimpleControllerHandlerAdapter 差不多,区别在于它判断是否为 javax.servlet.Servlet 对象,是的话则调用其 service 方法,返回该方法执行后返回的 ModelAndView 对象

AbstractHandlerMethodAdapter

org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter,实现 HandlerAdapter、Ordered 接口,继承 WebContentGenerator 抽象类,基于 HandlerMethod 的 HandlerMethodAdapter 抽象类

构造方法
  1. public abstract class AbstractHandlerMethodAdapter extends WebContentGenerator implements HandlerAdapter, Ordered {
  2. /** 最低优先级 */
  3. private int order = Ordered.LOWEST_PRECEDENCE;
  4. public AbstractHandlerMethodAdapter() {
  5. // no restriction of HTTP methods by default
  6. // 调用 WebContentGenerator 类的构造方法
  7. // 参数 restrictDefaultSupportedMethods 参数为 false ,表示不需要严格校验 HttpMethod
  8. super(false);
  9. }
  10. }
supports方法

实现 supports(Object handler) 方法,判断是否支持该处理器,代码如下:

  1. @Override
  2. public final boolean supports(Object handler) {
  3. return (handler instanceof HandlerMethod && supportsInternal((HandlerMethod) handler));
  4. }
  5. protected abstract boolean supportsInternal(HandlerMethod handlerMethod);
  • 还需要调用抽象方法 supportsInternal(HandlerMethod handlerMethod)判断是否支持, 交由子类去实现,详情见下文

handle方法

实现 handle(HttpServletRequest request, HttpServletResponse response, Object handler) 方法,用于处理请求,执行该处理器,代码如下:

  1. @Override
  2. @Nullable
  3. public final ModelAndView handle(HttpServletRequest request, HttpServletResponse response, Object handler)
  4. throws Exception {
  5. return handleInternal(request, response, (HandlerMethod) handler);
  6. }
  7. @Nullable
  8. protected abstract ModelAndView handleInternal(HttpServletRequest request,
  9. HttpServletResponse response, HandlerMethod handlerMethod) throws Exception;
  • 如果该 HandlerAdapter 支持这个处理器,那么则会调用该方法去处理请求,执行这个处理器

  • 直接调用 handleInternal(HttpServletRequest request, HttpServletResponse response, HandlerMethod handlerMethod) 抽象方法,交由子类去实现,详情见下文

getLastModified方法

实现 getLastModified(HttpServletRequest request, Object handler) 方法,获得最后更新时间,代码如下

  1. @Override
  2. public final long getLastModified(HttpServletRequest request, Object handler) {
  3. return getLastModifiedInternal(request, (HandlerMethod) handler);
  4. }
  5. protected abstract long getLastModifiedInternal(HttpServletRequest request, HandlerMethod handlerMethod);
  • 直接调用getLastModifiedInternal(HttpServletRequest request, HandlerMethod handlerMethod)抽象方法,交由子类去实现,详情见下文

RequestMappingHandlerAdapter

org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter,实现 BeanFactoryAware、InitializingBean 接口,继承 AbstractHandlerMethodAdapter 抽象类,基于 @RequestMapping 注解的 HandlerMethod 处理器的 HandlerMethodAdapter 实现类

构造方法
  1. public class RequestMappingHandlerAdapter extends AbstractHandlerMethodAdapter
  2. implements BeanFactoryAware, InitializingBean {
  3. /**
  4. * MethodFilter that matches {@link InitBinder @InitBinder} methods.
  5. */
  6. public static final MethodFilter INIT_BINDER_METHODS = method ->
  7. AnnotatedElementUtils.hasAnnotation(method, InitBinder.class);
  8. /**
  9. * MethodFilter that matches {@link ModelAttribute @ModelAttribute} methods.
  10. */
  11. public static final MethodFilter MODEL_ATTRIBUTE_METHODS = method ->
  12. (!AnnotatedElementUtils.hasAnnotation(method, RequestMapping.class) &&
  13. AnnotatedElementUtils.hasAnnotation(method, ModelAttribute.class));
  14. @Nullable
  15. private List<HandlerMethodArgumentResolver> customArgumentResolvers;
  16. @Nullable
  17. private HandlerMethodArgumentResolverComposite argumentResolvers;
  18. @Nullable
  19. private HandlerMethodArgumentResolverComposite initBinderArgumentResolvers;
  20. @Nullable
  21. private List<HandlerMethodReturnValueHandler> customReturnValueHandlers;
  22. @Nullable
  23. private HandlerMethodReturnValueHandlerComposite returnValueHandlers;
  24. @Nullable
  25. private List<ModelAndViewResolver> modelAndViewResolvers;
  26. private ContentNegotiationManager contentNegotiationManager = new ContentNegotiationManager();
  27. private List<HttpMessageConverter<?>> messageConverters;
  28. private List<Object> requestResponseBodyAdvice = new ArrayList<>();
  29. @Nullable
  30. private WebBindingInitializer webBindingInitializer;
  31. private AsyncTaskExecutor taskExecutor = new SimpleAsyncTaskExecutor("MvcAsync");
  32. @Nullable
  33. private Long asyncRequestTimeout;
  34. private CallableProcessingInterceptor[] callableInterceptors = new CallableProcessingInterceptor[0];
  35. private DeferredResultProcessingInterceptor[] deferredResultInterceptors = new DeferredResultProcessingInterceptor[0];
  36. private ReactiveAdapterRegistry reactiveAdapterRegistry = ReactiveAdapterRegistry.getSharedInstance();
  37. private boolean ignoreDefaultModelOnRedirect = false;
  38. private int cacheSecondsForSessionAttributeHandlers = 0;
  39. /**
  40. * 是否对相同 Session 加锁
  41. */
  42. private boolean synchronizeOnSession = false;
  43. private SessionAttributeStore sessionAttributeStore = new DefaultSessionAttributeStore();
  44. private ParameterNameDiscoverer parameterNameDiscoverer = new DefaultParameterNameDiscoverer();
  45. @Nullable
  46. private ConfigurableBeanFactory beanFactory;
  47. // ========== 缓存 ==========
  48. private final Map<Class<?>, SessionAttributesHandler> sessionAttributesHandlerCache = new ConcurrentHashMap<>(64);
  49. private final Map<Class<?>, Set<Method>> initBinderCache = new ConcurrentHashMap<>(64);
  50. private final Map<ControllerAdviceBean, Set<Method>> initBinderAdviceCache = new LinkedHashMap<>();
  51. private final Map<Class<?>, Set<Method>> modelAttributeCache = new ConcurrentHashMap<>(64);
  52. private final Map<ControllerAdviceBean, Set<Method>> modelAttributeAdviceCache = new LinkedHashMap<>();
  53. // ... 省略 getter、setter 方法
  54. public RequestMappingHandlerAdapter() {
  55. // 初始化 messageConverters
  56. StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter();
  57. stringHttpMessageConverter.setWriteAcceptCharset(false); // see SPR-7316
  58. this.messageConverters = new ArrayList<>(4);
  59. this.messageConverters.add(new ByteArrayHttpMessageConverter());
  60. this.messageConverters.add(stringHttpMessageConverter);
  61. try {
  62. this.messageConverters.add(new SourceHttpMessageConverter<>());
  63. }
  64. catch (Error err) {
  65. // Ignore when no TransformerFactory implementation is available
  66. }
  67. this.messageConverters.add(new AllEncompassingFormHttpMessageConverter());
  68. }
  69. }

有许多的属性,不着急理解,先列几个主要的属性对象:

  • HandlerMethodArgumentResolverComposite argumentResolvers:参数处理器组合对象

  • HandlerMethodReturnValueHandlerComposite returnValueHandlers:返回值处理器组合对象

  • List<HttpMessageConverter<?>> messageConverters:HTTP 消息转换器集合对象

  • List<Object> requestResponseBodyAdvice: RequestResponseAdvice 集合对象

在构造方法中默认会添加了四个 HttpMessageConverter 对象,当然,默认还会添加其他的,例如 MappingJackson2HttpMessageConverter 为 JSON 消息格式的转换器

1.afterPropertiesSet 初始化方法

因为 RequestMappingHandlerAdapter 实现了 InitializingBean 接口,在 Sping 初始化该 Bean 的时候,会调用该方法,完成一些初始化工作,方法如下:

  1. @Override
  2. public void afterPropertiesSet() {
  3. // Do this first, it may add ResponseBody advice beans
  4. // <1> 初始化 ControllerAdvice 相关
  5. initControllerAdviceCache();
  6. // <2> 初始化 argumentResolvers 属性
  7. if (this.argumentResolvers == null) {
  8. List<HandlerMethodArgumentResolver> resolvers = getDefaultArgumentResolvers();
  9. this.argumentResolvers = new HandlerMethodArgumentResolverComposite().addResolvers(resolvers);
  10. }
  11. // <3> 初始化 initBinderArgumentResolvers 属性
  12. if (this.initBinderArgumentResolvers == null) {
  13. List<HandlerMethodArgumentResolver> resolvers = getDefaultInitBinderArgumentResolvers();
  14. this.initBinderArgumentResolvers = new HandlerMethodArgumentResolverComposite().addResolvers(resolvers);
  15. }
  16. // <4> 初始化 returnValueHandlers 属性
  17. if (this.returnValueHandlers == null) {
  18. List<HandlerMethodReturnValueHandler> handlers = getDefaultReturnValueHandlers();
  19. this.returnValueHandlers = new HandlerMethodReturnValueHandlerComposite().addHandlers(handlers);
  20. }
  21. }
  1. 调用 initControllerAdviceCache() 方法,初始化 ControllerAdvice 相关,详情见下文

  1. 初始化 argumentResolvers 属性,调用 getDefaultArgumentResolvers() 方法,获得默认的 HandlerMethodArgumentResolver 数组,详情见下文

  1. 初始化 initBinderArgumentResolvers 属性,调用 getDefaultInitBinderArgumentResolvers() 方法,获得默认的 HandlerMethodArgumentResolver 数组,详情见下文

  1. 初始化 returnValueHandlers 属性,调用 getDefaultReturnValueHandlers() 方法,获得默认的 HandlerMethodReturnValueHandler 数组,详情见下文

1.1 initControllerAdviceCache

initControllerAdviceCache() 方法,初始化 ControllerAdvice 相关,方法如下:

  1. private void initControllerAdviceCache() {
  2. if (getApplicationContext() == null) {
  3. return;
  4. }
  5. // <1> 扫描 @ControllerAdvice 注解的 Bean 们,生成对应的 ControllerAdviceBean 对象,并将进行排序
  6. List<ControllerAdviceBean> adviceBeans = ControllerAdviceBean.findAnnotatedBeans(getApplicationContext());
  7. AnnotationAwareOrderComparator.sort(adviceBeans);
  8. List<Object> requestResponseBodyAdviceBeans = new ArrayList<>();
  9. // <2> 遍历 ControllerAdviceBean 数组
  10. for (ControllerAdviceBean adviceBean : adviceBeans) {
  11. Class<?> beanType = adviceBean.getBeanType();
  12. if (beanType == null) {
  13. throw new IllegalStateException("Unresolvable type for ControllerAdviceBean: " + adviceBean);
  14. }
  15. // <2.1> 扫描有 `@ModelAttribute` ,无 `@RequestMapping` 注解的方法,添加到 `modelAttributeAdviceCache` 属性中
  16. // 该类方法用于在执行方法前修改 Model 对象
  17. Set<Method> attrMethods = MethodIntrospector.selectMethods(beanType, MODEL_ATTRIBUTE_METHODS);
  18. if (!attrMethods.isEmpty()) {
  19. this.modelAttributeAdviceCache.put(adviceBean, attrMethods);
  20. }
  21. // <2.2> 扫描有 `@InitBinder` 注解的方法,添加到 `initBinderAdviceCache` 属性中
  22. // 该类方法用于在执行方法前初始化数据绑定器
  23. Set<Method> binderMethods = MethodIntrospector.selectMethods(beanType, INIT_BINDER_METHODS);
  24. if (!binderMethods.isEmpty()) {
  25. this.initBinderAdviceCache.put(adviceBean, binderMethods);
  26. }
  27. // <2.3> 如果是 RequestBodyAdvice 或 ResponseBodyAdvice 的子类,添加到 requestResponseBodyAdviceBeans 中
  28. if (RequestBodyAdvice.class.isAssignableFrom(beanType) || ResponseBodyAdvice.class.isAssignableFrom(beanType)) {
  29. requestResponseBodyAdviceBeans.add(adviceBean);
  30. }
  31. }
  32. // <2.3> 将 requestResponseBodyAdviceBeans 添加到 this.requestResponseBodyAdvice 属性种
  33. if (!requestResponseBodyAdviceBeans.isEmpty()) {
  34. this.requestResponseBodyAdvice.addAll(0, requestResponseBodyAdviceBeans);
  35. }
  36. // 打印日志
  37. if (logger.isDebugEnabled()) {
  38. int modelSize = this.modelAttributeAdviceCache.size();
  39. int binderSize = this.initBinderAdviceCache.size();
  40. int reqCount = getBodyAdviceCount(RequestBodyAdvice.class);
  41. int resCount = getBodyAdviceCount(ResponseBodyAdvice.class);
  42. if (modelSize == 0 && binderSize == 0 && reqCount == 0 && resCount == 0) {
  43. logger.debug("ControllerAdvice beans: none");
  44. }
  45. else {
  46. logger.debug("ControllerAdvice beans: " + modelSize + " @ModelAttribute, " + binderSize +
  47. " @InitBinder, " + reqCount + " RequestBodyAdvice, " + resCount + " ResponseBodyAdvice");
  48. }
  49. }
  50. }

从 Spring 上下文扫描 @ControllerAdvice 注解的 Bean 们,生成对应的 ControllerAdviceBean 对象,并将进行排序,方法如下:

  1. public static List<ControllerAdviceBean> findAnnotatedBeans(ApplicationContext context) {
  2. return Arrays.stream(BeanFactoryUtils.beanNamesForTypeIncludingAncestors(context, Object.class))
  3. // 排除代理目标类,AOP 相关
  4. .filter(name -> !ScopedProxyUtils.isScopedTarget(name))
  5. // 包含 @ControllerAdvice 注解
  6. .filter(name -> context.findAnnotationOnBean(name, ControllerAdvice.class) != null)
  7. // 生成对应的 ControllerAdviceBean 对象
  8. .map(name -> new ControllerAdviceBean(name, context))
  9. .collect(Collectors.toList());
  10. }
  1. @ControllerAdvice 注解:用于 Controller 类的增强类,其中可定义多种增强的方法,例如 @ExceptionHandler 注解的方法用于处理器 Controller 抛出的异常

  1. 遍历 1 中生成 ControllerAdviceBean 数组

  1. 扫描 @ModelAttribute @RequestMapping 注解的方法,添加到 modelAttributeAdviceCache 属性中,该类方法用于在执行方法前修改 Model 对象

  1. 扫描 @InitBinder 注解的方法,添加到 initBinderAdviceCache 属性中,该类方法用于在执行方法前初始化数据绑定器

  1. 如果是 RequestBodyAdvice 或 ResponseBodyAdvice 的子类,保存至 requestResponseBodyAdviceBeans 临时变量中

  1. 2.c 的 requestResponseBodyAdviceBeans 保存至 requestResponseBodyAdvice 属性中

1.2 getDefaultArgumentResolvers

getDefaultArgumentResolvers(),初始化默认的参数解析器,方法如下:

  1. private List<HandlerMethodArgumentResolver> getDefaultArgumentResolvers() {
  2. List<HandlerMethodArgumentResolver> resolvers = new ArrayList<>();
  3. // Annotation-based argument resolution
  4. resolvers.add(new RequestParamMethodArgumentResolver(getBeanFactory(), false));
  5. resolvers.add(new RequestParamMapMethodArgumentResolver());
  6. resolvers.add(new PathVariableMethodArgumentResolver());
  7. resolvers.add(new PathVariableMapMethodArgumentResolver());
  8. resolvers.add(new MatrixVariableMethodArgumentResolver());
  9. resolvers.add(new MatrixVariableMapMethodArgumentResolver());
  10. resolvers.add(new ServletModelAttributeMethodProcessor(false));
  11. resolvers.add(new RequestResponseBodyMethodProcessor(getMessageConverters(), this.requestResponseBodyAdvice));
  12. resolvers.add(new RequestPartMethodArgumentResolver(getMessageConverters(), this.requestResponseBodyAdvice));
  13. resolvers.add(new RequestHeaderMethodArgumentResolver(getBeanFactory()));
  14. resolvers.add(new RequestHeaderMapMethodArgumentResolver());
  15. resolvers.add(new ServletCookieValueMethodArgumentResolver(getBeanFactory()));
  16. resolvers.add(new ExpressionValueMethodArgumentResolver(getBeanFactory()));
  17. resolvers.add(new SessionAttributeMethodArgumentResolver());
  18. resolvers.add(new RequestAttributeMethodArgumentResolver());
  19. // Type-based argument resolution
  20. resolvers.add(new ServletRequestMethodArgumentResolver());
  21. resolvers.add(new ServletResponseMethodArgumentResolver());
  22. resolvers.add(new HttpEntityMethodProcessor(getMessageConverters(), this.requestResponseBodyAdvice));
  23. resolvers.add(new RedirectAttributesMethodArgumentResolver());
  24. resolvers.add(new ModelMethodProcessor());
  25. resolvers.add(new MapMethodProcessor());
  26. resolvers.add(new ErrorsMethodArgumentResolver());
  27. resolvers.add(new SessionStatusMethodArgumentResolver());
  28. resolvers.add(new UriComponentsBuilderMethodArgumentResolver());
  29. // Custom arguments
  30. if (getCustomArgumentResolvers() != null) {
  31. resolvers.addAll(getCustomArgumentResolvers());
  32. }
  33. // Catch-all
  34. resolvers.add(new RequestParamMethodArgumentResolver(getBeanFactory(), true));
  35. resolvers.add(new ServletModelAttributeMethodProcessor(true));
  36. return resolvers;
  37. }
1.3 getDefaultReturnValueHandlers

getDefaultReturnValueHandlers(),初始化默认的返回值处理器,方法如下:

  1. private List<HandlerMethodReturnValueHandler> getDefaultReturnValueHandlers() {
  2. List<HandlerMethodReturnValueHandler> handlers = new ArrayList<>();
  3. // Single-purpose return value types
  4. handlers.add(new ModelAndViewMethodReturnValueHandler());
  5. handlers.add(new ModelMethodProcessor());
  6. handlers.add(new ViewMethodReturnValueHandler());
  7. handlers.add(new ResponseBodyEmitterReturnValueHandler(getMessageConverters(),
  8. this.reactiveAdapterRegistry, this.taskExecutor, this.contentNegotiationManager));
  9. handlers.add(new StreamingResponseBodyReturnValueHandler());
  10. handlers.add(new HttpEntityMethodProcessor(getMessageConverters(),
  11. this.contentNegotiationManager, this.requestResponseBodyAdvice));
  12. handlers.add(new HttpHeadersReturnValueHandler());
  13. handlers.add(new CallableMethodReturnValueHandler());
  14. handlers.add(new DeferredResultMethodReturnValueHandler());
  15. handlers.add(new AsyncTaskMethodReturnValueHandler(this.beanFactory));
  16. // Annotation-based return value types
  17. handlers.add(new ModelAttributeMethodProcessor(false));
  18. handlers.add(new RequestResponseBodyMethodProcessor(getMessageConverters(),
  19. this.contentNegotiationManager, this.requestResponseBodyAdvice));
  20. // Multi-purpose return value types
  21. handlers.add(new ViewNameMethodReturnValueHandler());
  22. handlers.add(new MapMethodProcessor());
  23. // Custom return value types
  24. if (getCustomReturnValueHandlers() != null) {
  25. handlers.addAll(getCustomReturnValueHandlers());
  26. }
  27. // Catch-all
  28. if (!CollectionUtils.isEmpty(getModelAndViewResolvers())) {
  29. handlers.add(new ModelAndViewResolverMethodReturnValueHandler(getModelAndViewResolvers()));
  30. }
  31. else {
  32. handlers.add(new ModelAttributeMethodProcessor(true));
  33. }
  34. return handlers;
  35. }
  • 按顺序添加了非常多的返回值处理器对象

supportsInternal 方法

实现 supportsInternal() 接口,方法如下:

  1. @Override
  2. protected boolean supportsInternal(HandlerMethod handlerMethod) {
  3. return true;
  4. }

直接返回 true,也就是说处理器只要是 HandlerMethod 对象就可以

getLastModifiedInternal 方法
  1. @Override
  2. protected long getLastModifiedInternal(HttpServletRequest request, HandlerMethod handlerMethod) {
  3. return -1;
  4. }

直接返回 -1

handleInternal 方法

实现 handleInternal(HttpServletRequest request, HttpServletResponse response, HandlerMethod handlerMethod) 方法,处理请求,执行处理器,方法如下:

  1. @Override
  2. protected ModelAndView handleInternal(HttpServletRequest request, HttpServletResponse response,
  3. HandlerMethod handlerMethod) throws Exception {
  4. ModelAndView mav;
  5. // <1> 校验请求(HttpMethod 和 Session 的校验)
  6. checkRequest(request);
  7. // <2> 调用 HandlerMethod 方法
  8. // Execute invokeHandlerMethod in synchronized block if required.
  9. if (this.synchronizeOnSession) { // 同步相同 Session 的逻辑,默认情况false
  10. HttpSession session = request.getSession(false);
  11. if (session != null) {
  12. // 获取Session的锁对象
  13. Object mutex = WebUtils.getSessionMutex(session);
  14. synchronized (mutex) {
  15. mav = invokeHandlerMethod(request, response, handlerMethod);
  16. }
  17. }
  18. else {
  19. // No HttpSession available -> no mutex necessary
  20. mav = invokeHandlerMethod(request, response, handlerMethod);
  21. }
  22. } else {
  23. // No synchronization on session demanded at all...
  24. mav = invokeHandlerMethod(request, response, handlerMethod);
  25. }
  26. if (!response.containsHeader(HEADER_CACHE_CONTROL)) { // 响应不包含'Cache-Control'头
  27. if (getSessionAttributesHandler(handlerMethod).hasSessionAttributes()) {
  28. applyCacheSeconds(response, this.cacheSecondsForSessionAttributeHandlers);
  29. }
  30. else {
  31. prepareResponse(response);
  32. }
  33. }
  34. return mav;
  35. }

1、调用父类 WebContentGenerator 的 checkRequest(ttpServletRequest request) 方法,校验请求(HttpMethod 和 Session)是否合法

  1. protected final void checkRequest(HttpServletRequest request) throws ServletException {
  2. // Check whether we should support the request method.
  3. String method = request.getMethod();
  4. if (this.supportedMethods != null && !this.supportedMethods.contains(method)) {
  5. throw new HttpRequestMethodNotSupportedException(method, this.supportedMethods);
  6. }
  7. // Check whether a session is required.
  8. if (this.requireSession && request.getSession(false) == null) {
  9. throw new HttpSessionRequiredException("Pre-existing session required but none found");
  10. }
  11. }

在 AbstractHandlerMethodAdapter 的构造方法中,传入 restrictDefaultSupportedMethods 参数为 false,表示不需要严格校验 HttpMethod,这里正常情况都会校验通过

2、调用 invokeHandlerMethod(HttpServletRequest request, HttpServletResponse response, HandlerMethod handlerMethod) 方法,执行 HandlerMethod 处理器

这里会判断 synchronizeOnSession 属性,控制是否同步相同 Session 的逻辑,其中 WebUtils#getSessionMutex(session) 方法,用来获得锁的对象,方法如下:

  1. public static Object getSessionMutex(HttpSession session) {
  2. Assert.notNull(session, "Session must not be null");
  3. Object mutex = session.getAttribute(SESSION_MUTEX_ATTRIBUTE);
  4. if (mutex == null) {
  5. mutex = session;
  6. }
  7. return mutex;
  8. }

当然,因为锁是通过 synchronized 是 JVM 进程级,所以在分布式环境下,无法达到同步相同 Session 的功能

默认情况下,synchronizeOnSessionfalse


【重点】invokeHandlerMethod方法

invokeHandlerMethod(HttpServletRequest request, HttpServletResponse response, HandlerMethod handlerMethod) 方法,执行 HandlerMethod 处理器,方法如下:

  1. @Nullable
  2. protected ModelAndView invokeHandlerMethod(HttpServletRequest request, HttpServletResponse response,
  3. HandlerMethod handlerMethod) throws Exception {
  4. // <1> 创建 ServletWebRequest 对象
  5. ServletWebRequest webRequest = new ServletWebRequest(request, response);
  6. try {
  7. // <2> 创建 WebDataBinderFactory 对象
  8. WebDataBinderFactory binderFactory = getDataBinderFactory(handlerMethod);
  9. // <3> 创建 ModelFactory 对象
  10. ModelFactory modelFactory = getModelFactory(handlerMethod, binderFactory);
  11. // <4> 创建 ServletInvocableHandlerMethod 对象,并设置其相关属性
  12. ServletInvocableHandlerMethod invocableMethod = createInvocableHandlerMethod(handlerMethod);
  13. if (this.argumentResolvers != null) {
  14. invocableMethod.setHandlerMethodArgumentResolvers(this.argumentResolvers);
  15. }
  16. if (this.returnValueHandlers != null) {
  17. invocableMethod.setHandlerMethodReturnValueHandlers(this.returnValueHandlers);
  18. }
  19. invocableMethod.setDataBinderFactory(binderFactory);
  20. invocableMethod.setParameterNameDiscoverer(this.parameterNameDiscoverer);
  21. // <5> 创建 ModelAndViewContainer 对象,并初始其相关属性
  22. ModelAndViewContainer mavContainer = new ModelAndViewContainer();
  23. mavContainer.addAllAttributes(RequestContextUtils.getInputFlashMap(request));
  24. modelFactory.initModel(webRequest, mavContainer, invocableMethod);
  25. mavContainer.setIgnoreDefaultModelOnRedirect(this.ignoreDefaultModelOnRedirect);
  26. // <6> 创建 AsyncWebRequest 异步请求对象
  27. AsyncWebRequest asyncWebRequest = WebAsyncUtils.createAsyncWebRequest(request, response);
  28. asyncWebRequest.setTimeout(this.asyncRequestTimeout);
  29. // <7> 创建 WebAsyncManager 异步请求管理器对象
  30. WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
  31. asyncManager.setTaskExecutor(this.taskExecutor);
  32. asyncManager.setAsyncWebRequest(asyncWebRequest);
  33. asyncManager.registerCallableInterceptors(this.callableInterceptors);
  34. asyncManager.registerDeferredResultInterceptors(this.deferredResultInterceptors);
  35. // <8>
  36. if (asyncManager.hasConcurrentResult()) {
  37. Object result = asyncManager.getConcurrentResult();
  38. mavContainer = (ModelAndViewContainer) asyncManager.getConcurrentResultContext()[0];
  39. asyncManager.clearConcurrentResult();
  40. LogFormatUtils.traceDebug(logger, traceOn -> {
  41. String formatted = LogFormatUtils.formatValue(result, !traceOn);
  42. return "Resume with async result [" + formatted + "]";
  43. });
  44. invocableMethod = invocableMethod.wrapConcurrentResult(result);
  45. }
  46. // <9> 执行调用
  47. invocableMethod.invokeAndHandle(webRequest, mavContainer);
  48. // <10>
  49. if (asyncManager.isConcurrentHandlingStarted()) {
  50. return null;
  51. }
  52. // <11> 获得 ModelAndView 对象
  53. return getModelAndView(mavContainer, modelFactory, webRequest);
  54. }
  55. finally {
  56. // <12> 标记请求完成
  57. webRequest.requestCompleted();
  58. }
  59. }

因为,Spring MVC 提供了大量的特性,所以 HandlerAdapter 又涉及许多组件。我们主要先梳理好主流程,所以涉及的组件,还是先不详细解析。我们的目的是,看到怎么调用 HandlerMethod 方法的,即调用 Controller 的 @RequestMapping 注解的方法。

  1. 创建 ServletWebRequest 对象,包含了 request 请求和 response响应

  1. 调用 getDataBinderFactory(HandlerMethod handlerMethod) 方法,创建 WebDataBinderFactory 对象,有关于数据绑定,暂时忽略

  1. 调用 getModelFactory(HandlerMethod handlerMethod, WebDataBinderFactory binderFactory) 方法,创建 ModelFactory 对象,有关于往 Model 对象设置数据,暂时忽略

  1. 【核心】调用 createInvocableHandlerMethod(HandlerMethod handlerMethod) 方法,创建 ServletInvocableHandlerMethod 对象,然后设置其属性。本文会对 ServletInvocableHandlerMethod 做简单的解析。

  1. 创建 ModelAndViewContainer 对象,并初始其相关属性

  1. 创建 AsyncWebRequest 异步请求对象,暂时忽略

  1. 创建 WebAsyncManager 异步请求管理器对象,暂时忽略

  1. 异步处理,并发结果相关,暂时忽略

9、【核心】调用 ServletInvocableHandlerMethodinvokeAndHandle(ServletWebRequest webRequest, ModelAndViewContainer mavContainer, Object... providedArgs) 方法,执行处理器,方法如下:

  1. // ServletInvocableHandlerMethod.java
  2. public void invokeAndHandle(ServletWebRequest webRequest, ModelAndViewContainer mavContainer,
  3. Object... providedArgs) throws Exception {
  4. // <1> 执行调用
  5. Object returnValue = invokeForRequest(webRequest, mavContainer, providedArgs);
  6. // <2> 设置响应状态码
  7. setResponseStatus(webRequest);
  8. // <3> 设置 ModelAndViewContainer 为请求已处理,返回,和 @ResponseStatus 注解相关
  9. if (returnValue == null) {
  10. if (isRequestNotModified(webRequest) || getResponseStatus() != null || mavContainer.isRequestHandled()) {
  11. disableContentCachingIfNecessary(webRequest);
  12. mavContainer.setRequestHandled(true);
  13. return;
  14. }
  15. } else if (StringUtils.hasText(getResponseStatusReason())) {
  16. mavContainer.setRequestHandled(true);
  17. return;
  18. }
  19. // <4> 设置 ModelAndViewContainer 为请求未处理
  20. mavContainer.setRequestHandled(false);
  21. Assert.state(this.returnValueHandlers != null, "No return value handlers");
  22. try {
  23. // <5> 处理返回值
  24. this.returnValueHandlers.handleReturnValue(returnValue, getReturnValueType(returnValue), mavContainer, webRequest);
  25. } catch (Exception ex) {
  26. if (logger.isTraceEnabled()) {
  27. logger.trace(formatErrorForReturnValue(returnValue), ex);
  28. }
  29. throw ex;
  30. }
  31. }
  32. // InvocableHandlerMethod.java
  33. @Nullable
  34. public Object invokeForRequest(NativeWebRequest request, @Nullable ModelAndViewContainer mavContainer,
  35. Object... providedArgs) throws Exception {
  36. // <y> 解析参数
  37. Object[] args = getMethodArgumentValues(request, mavContainer, providedArgs);
  38. if (logger.isTraceEnabled()) {
  39. logger.trace("Arguments: " + Arrays.toString(args));
  40. }
  41. // 执行调用
  42. return doInvoke(args);
  43. }
  44. // InvocableHandlerMethod.java
  45. @Nullable
  46. protected Object doInvoke(Object... args) throws Exception {
  47. // <z1> 设置方法为可访问
  48. ReflectionUtils.makeAccessible(getBridgedMethod());
  49. try {
  50. // <z2> 执行调用
  51. return getBridgedMethod().invoke(getBean(), args);
  52. } catch (IllegalArgumentException ex) {
  53. assertTargetBean(getBridgedMethod(), getBean(), args);
  54. String text = (ex.getMessage() != null ? ex.getMessage() : "Illegal argument");
  55. throw new IllegalStateException(formatInvokeError(text, args), ex);
  56. } catch (InvocationTargetException ex) {
  57. // Unwrap for HandlerExceptionResolvers ...
  58. Throwable targetException = ex.getTargetException();
  59. if (targetException instanceof RuntimeException) {
  60. throw (RuntimeException) targetException;
  61. }
  62. else if (targetException instanceof Error) {
  63. throw (Error) targetException;
  64. }
  65. else if (targetException instanceof Exception) {
  66. throw (Exception) targetException;
  67. }
  68. else {
  69. throw new IllegalStateException(formatInvokeError("Invocation failure", args), targetException);
  70. }
  71. }
  72. }

可以大致过一下上面的执行逻辑,解析参数,通过反射执行方法,解析执行结果

  1. 异步处理,并发结果相关,暂时忽略

  1. 调用

getModelAndView(ModelAndViewContainer mavContainer, ModelFactory modelFactory, NativeWebRequest webRequest) 方法,获得 ModelAndView 对象,方法如下:

  1. @Nullable
  2. private ModelAndView getModelAndView(ModelAndViewContainer mavContainer,
  3. ModelFactory modelFactory, NativeWebRequest webRequest) throws Exception {
  4. modelFactory.updateModel(webRequest, mavContainer);
  5. // 情况一,如果 mavContainer 已处理,则返回“空”的 ModelAndView 对象。
  6. if (mavContainer.isRequestHandled()) {
  7. return null;
  8. }
  9. // 情况二,如果 mavContainer 未处理,则基于 `mavContainer` 生成 ModelMap 对象
  10. ModelMap model = mavContainer.getModel();
  11. // 创建 ModelAndView 对象,并设置相关属性
  12. ModelAndView mav = new ModelAndView(mavContainer.getViewName(), model, mavContainer.getStatus());
  13. if (!mavContainer.isViewReference()) {
  14. mav.setView((View) mavContainer.getView());
  15. }
  16.     // FlashMap保持处理
  17. if (model instanceof RedirectAttributes) {
  18. Map<String, ?> flashAttributes = ((RedirectAttributes) model).getFlashAttributes();
  19. HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
  20. if (request != null) {
  21. RequestContextUtils.getOutputFlashMap(request).putAll(flashAttributes);
  22. }
  23. }
  24. return mav;
  25. }
  • 情况一,如果 mavContainer 已处理,则返回“空”的 ModelAndView 对象,@ResponseBody 注解的结果处理则直接返回 null

  • 情况二,如果 mavContainer 未处理,则基于 mavContainer 生成 ModelAndView 对象

  1. 在后续的文档分析中会讲到,注意这里的 requestHandled 属性,到时候再回过头来理解

    声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/在线问答5/article/detail/917127
推荐阅读
相关标签