1. 下图是springmvc的执行流程

    图片来源:https://www.jianshu.com/p/8a20c547e245


     DispatcherServlet根据url定位到Controller和方法,依赖的是HandlerMapping接口的各个实现类,其中,RequestMappingHandlerMapping是专门用来处理注解方式的Controller的

    下面,我们分RequestMappingHandlerMapping的加载以及RequestMappingHandlerMapping如何根据url定位Controller两部分来讲

    RequestMappingHandlerMapping加载过程

    1. RMHP在系统启动时会被注册成bean,见《springmvc源码笔记-HandlerMapping注入》

    2. 因为RMHP实现了InitializingBean接口,在bean加载完成后会自动调用afterPropertiesSet方法,在此方法中调用了AbstractHandlerMethodMapping#initHandlerMethods()来实现初始化

      protected void initHandlerMethods() {
      // 遍历所有的bean
      for (String beanName : getCandidateBeanNames()) {
      if (!beanName.startsWith(SCOPED_TARGET_NAME_PREFIX)) {
      processCandidateBean(beanName);
      }
      }
      handlerMethodsInitialized(getHandlerMethods());
      } protected void processCandidateBean(String beanName) {
      Class<?> beanType = null;
      try {
      beanType = obtainApplicationContext().getType(beanName);
      }
      ......
      // isHandler判断类是否有Controller或者RequestMapping注解
      if (beanType != null && isHandler(beanType)) {
      detectHandlerMethods(beanName);
      }
      } protected void detectHandlerMethods(Object handler) {
      ......
      if (handlerType != null) {
      Class<?> userType = ClassUtils.getUserClass(handlerType);
      // 遍历类的所有方法
      Map<Method, T> methods = MethodIntrospector.selectMethods(userType,
      (MethodIntrospector.MetadataLookup<T>) method -> {
      try {
      // 获取方法上的映射(会读取方法上的RequestMapping注解获取url)
      return getMappingForMethod(method, userType);
      }
      catch (Throwable ex) {
      throw new IllegalStateException("Invalid mapping on handler class [" +
      userType.getName() + "]: " + method, ex);
      }
      });
      ......
      methods.forEach((method, mapping) -> {
      Method invocableMethod = AopUtils.selectInvocableMethod(method, userType);
      // 将映射关系放入AbstractHandlerMethodMapping.mappingRegistry中
      registerHandlerMethod(handler, invocableMethod, mapping);
      });
      }
      }

    RequestMappingHandlerMapping解析过程

    1. DispatcherServlet继承HttpServlet,所以执行链是FrameworkServlet#doGet→DispatcherServlet#doService→DispatcherServlet#doDispatch→DispatcherServlet#getHandler

      protected HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception {
      if (this.handlerMappings != null) {
      // handlerMappings已在onRefresh方法中初始化
      for (HandlerMapping mapping : this.handlerMappings) {
      // 第一个mapping就是RequestMappingHandlerMapping
      // 获取处理程序,也就是url对应的controller和method
      HandlerExecutionChain handler = mapping.getHandler(request);
      if (handler != null) {
      return handler;
      }
      }
      }
      return null;
      } // AbstractHandlerMapping#getHandler->RequestMappingHandlerMapping#getHandlerInternal->AbstractHandlerMapping#lookupHandlerMethod
      protected HandlerMethod lookupHandlerMethod(String lookupPath, HttpServletRequest request) throws Exception {
      // lookupPath就是请求路径
      List<Match> matches = new ArrayList<>();
      // 获取url路径匹配项
      List<T> directPathMatches = this.mappingRegistry.getMappingsByDirectPath(lookupPath);
      if (directPathMatches != null) {
      // 添加映射匹配集合
      addMatchingMappings(directPathMatches, matches, request);
      }
      if (matches.isEmpty()) {
      addMatchingMappings(this.mappingRegistry.getRegistrations().keySet(), matches, request);
      }
      if (!matches.isEmpty()) {
      ......
      // 至此,根据url获取到controller和method
      return bestMatch.getHandlerMethod();
      } else {
      return handleNoMatch(this.mappingRegistry.getRegistrations().keySet(), lookupPath, request);
      }
      } private void addMatchingMappings(Collection<T> mappings, List<Match> matches, HttpServletRequest request) {
      for (T mapping : mappings) {
      T match = getMatchingMapping(mapping, request);
      if (match != null) {
      // this.mappingRegistry.getRegistrations().get(mapping)就是获取HandlerMethodMapping
      // HandlerMethodMapping保存controller和method信息的类
      matches.add(new Match(match, this.mappingRegistry.getRegistrations().get(mapping)));
      }
      }
      }

springmvc源码笔记-RequestMappingHandlerMapping的更多相关文章

  1. springmvc源码笔记-HandlerMapping注入

    在springmvc中,如何根据url找到controller以及对应方法,依赖的是HandlerMapping接口的getHandler方法 在spring容器中默认注册的HandlerMappin ...

  2. springMVC源码笔记

    springMVC 设计总览 下图来源:https://www.cnblogs.com/fangjian0423/p/springMVC-directory-summary.html 下图来源:htt ...

  3. springmvc源码笔记-HandlerMethodReturnValueHandler

    返回值解析器 用于对controller的返回值进行二次处理 结构 // 返回值解析器 public interface HandlerMethodReturnValueHandler { // 判断 ...

  4. SpringMVC源码情操陶冶-AnnotationDrivenBeanDefinitionParser注解解析器

    mvc:annotation-driven节点的解析器,是springmvc的核心解析器 官方注释 Open Declaration org.springframework.web.servlet.c ...

  5. SpringMVC源码情操陶冶-DispatcherServlet简析(二)

    承接前文SpringMVC源码情操陶冶-DispatcherServlet类简析(一),主要讲述初始化的操作,本文将简单介绍springmvc如何处理请求 DispatcherServlet#doDi ...

  6. SpringMVC源码情操陶冶-AbstractHandlerMethodMapping

    承接前文SpringMVC源码情操陶冶-AbstractHandlerMapping,本文将介绍如何注册HandlerMethod对象作为handler 类结构瞧一瞧 public abstract ...

  7. SpringMVC源码情操陶冶-RequestMappingHandlerAdapter适配器

    承接前文SpringMVC源码情操陶冶-HandlerAdapter适配器简析.RequestMappingHandlerAdapter适配器组件是专门处理RequestMappingHandlerM ...

  8. springMVC源码分析--AbstractHandlerMethodMapping注册url和HandlerMethod对应关系(十一)

    在上一篇博客springMVC源码分析--AbstractHandlerMethodMapping获取url和HandlerMethod对应关系(十)中我们简单地介绍了获取url和HandlerMet ...

  9. SpringMVC源码阅读:拦截器

    1.前言 SpringMVC是目前J2EE平台的主流Web框架,不熟悉的园友可以看SpringMVC源码阅读入门,它交代了SpringMVC的基础知识和源码阅读的技巧 本文将通过源码(基于Spring ...

随机推荐

  1. Mac 系统用mx master3遇到的问题

    买 master3 之前上网看到的资料都是夸的不行,提到的问题也都是无足轻重,然而就我个人来说,在 Mac 下实际使用 master3 的感受很糟糕,写这篇文章分享一下遇到的问题,如果有想买的人看到这 ...

  2. RabbitMQ 3.9( 基础 )

    1.认识MQ 1.1.什么是MQ? MQ全称:message queue 即 消息队列 这个队列遵循的原则:FIFO 即 先进先出 队列里面存的就是message 1.2.为什么要用MQ? 1.2.1 ...

  3. 常见的邮箱服务器(SMTP,POP3)地址,端口

    163.com: POP3服务器地址:pop.163.com(端口:110) SMTP服务器地址:smtp.163.com(端口:25) sina.com: POP3服务器地址:pop3.sina.c ...

  4. 【mq】从零开始实现 mq-13-注册鉴权 auth

    前景回顾 [mq]从零开始实现 mq-01-生产者.消费者启动 [mq]从零开始实现 mq-02-如何实现生产者调用消费者? [mq]从零开始实现 mq-03-引入 broker 中间人 [mq]从零 ...

  5. Cocos---监听、触摸事件、坐标系转换

    监听.触摸事件.坐标系转换 Creator的系统事件 分为"节点系统事件"和"全局系统事件". 节点系统事件:触发在节点上,包括鼠标事件和触摸事件. 全局系统事 ...

  6. DeepPrivacy: A Generative Adversarial Network for Face Anonymization阅读笔记

    DeepPrivacy: A Generative Adversarial Network for Face Anonymization ISVC 2019 https://arxiv.org/pdf ...

  7. 安装Samba到CentOS(YUM)

    运行环境 系统版本:CentOS Linux release 7.3.1611 软件版本:Samba-4.6.2 硬件要求:无 安装过程 1.基础网络配置 配置一个静态IP,关闭防火墙.SeLinux ...

  8. mac安装git、node

    1.需要先安装homebrew(之前的文章里有) 2.安装git brew install git 3.安装node brew install node 3.1.安装成功后,查看版本号 node -v ...

  9. Mac下iTerm2安装rzsz后上传下载失败解决

    背景描述 mac环境,安装了iTerm2,需要使用ssh登陆linux服务器.服务器登陆需要经过以下步骤 输入token 输入登陆选项 输入IP 因此写了expect脚本来完成自动输入 但是在上传下载 ...

  10. 解锁!玩转 HelloGitHub 的新姿势

    本文不会涉及太多技术细节和源码,请放心食用 大家好,我是 HelloGitHub 的老荀,好久不见啊! 我在完成 HelloZooKeeper 系列之后,就很少"露面了".但是我对 ...