天天用Spring MVC,了解过它的底层源码吗?

作者:微信小助手

发布时间:2019-04-25T08:35:14

还没关注?伸出中指点这里!


聊技术、论职场!
为IT人打造一个“有温度”的狸猫技术窝

来源:http://yg1.top/8rTVMo

目录:

一、Spring MVC请求处理流程

二、Spring MVC的工作机制

三、Spring MVC核心源码分析

四、Spring MVC的优化



一、Spring MVC请求处理流程


引用spring in action上的一张图来说明了springmvc的核心组件和请求处理流程:

         

  1. DispatcherServlet是springmvc中的前端控制器(front controller),负责接收request并将request转发给对应的处理组件.


  2. HanlerMapping是springmvc中完成url到controller映射的组件.DispatcherServlet接收request,然后从HandlerMapping查找处理request的controller.


  3. Controller处理request,并返回ModelAndView对象,Controller是springmvc中负责处理request的组件(类似于struts2中的Action),ModelAndView是封装结果视图的组件.


  4. ④ ⑤ ⑥:视图解析器解析ModelAndView对象并返回对应的视图给客户端.




二、Spring MVC的工作机制


在容器初始化时会建立所有url和controller的对应关系,保存到Map 中.


tomcat启动时会通知spring初始化容器(加载bean的定义信息和初始化所有单例bean).


然后springmvc会遍历容器中的bean,获取每一个controller中的所有方法访问的url,然后将url和controller保存到一个Map中;


这样,就可以根据request快速定位到controller,因为最终处理request的是controller中的方法,Map中只保留了url和controller中的对应关系,所以要根据request的url进一步确认controller中的method。


这一步工作的原理就是拼接controller的url(controller上@RequestMapping的值)和方法的url(method上@RequestMapping的值),与request的url进行匹配,找到匹配的那个方法;

  

确定处理请求的method后,接下来的任务就是参数绑定,把request中参数绑定到方法的形式参数上


这一步是整个请求处理过程中最复杂的一个步骤。springmvc提供了两种request参数与方法形参的绑定方法:


  1. 通过注解进行绑定,@RequestParam

  2. 通过参数名称进行绑定.


使用注解进行绑定,我们只要在方法参数前面声明@RequestParam("a"),就可以将request中参数a的值绑定到方法的该参数上.


使用参数名称进行绑定的前提是必须要获取方法中参数的名称,Java反射只提供了获取方法的参数的类型,并没有提供获取参数名称的方法.


Spring MVC解决这个问题的方法是用asm框架读取字节码文件,来获取方法的参数名称。asm框架是一个字节码操作框架。


个人建议,使用注解来完成参数绑定,这样就可以省去asm框架的读取字节码的操作.



三、Spring MVC核心源码分析


我们根据工作机制中三部分来分析 Spring MVC 的源代码.


  1. ApplicationContext初始化时建立所有url和controller类的对应关系(用Map保存);


  2. 根据请求url找到对应的controller,并从controller中找到处理请求的方法;


  3. request参数绑定到方法的形参,执行方法处理请求,并返回结果视图.


第一步、建立Map 的关系

首先看第一个步骤,也就是建立Map 关系的部分. 第一部分的入口类为ApplicationObjectSupport的setApplicationContext方法.


setApplicationContext方法中核心部分就是初始化容器initApplicationContext(context),子类AbstractDetectingUrlHandlerMapping实现了该方法,所以我们直接看子类中的初始化容器方法.


public void initApplicationContext() throws ApplicationContextException {
  super.initApplicationContext();
  detectHandlers();
}

/**
* 建立当前ApplicationContext中的所有controller和url的对应关系
*/

protected void detectHandlers() throws BeansException {
  if (logger.isDebugEnabled()) {
    logger.debug("Looking for URL mappings in application context: " + getApplicationContext());
  }
  
  // 获取ApplicationContext容器中所有bean的Name
  String[] beanNames = (this.detectHandlersInAncestorContexts ?
  BeanFactoryUtils.beanNamesForTypeIncludingAncestors(getApplicationContext(), Object.class) :
  getApplicationContext().getBeanNamesForType(Object.class));

  // 遍历beanNames,并找到这些bean对应的url
  for (String beanName : beanNames) {
  
    // 找bean上的所有url(controller上的url+方法上的url),该方法由对应的子类实现

    String[] urls = determineUrlsForHandler(beanName);
    if (!ObjectUtils.isEmpty(urls)) {
      // 保存urls和beanName的对应关系,put it to Map ,该方法在父类AbstractUrlHandlerMapping中实现
      registerHandler(urls, beanName);
    }
    else {
      if (logger.isDebugEnabled()) {
        logger.debug("Rejected bean name '" + beanName + "': no URL paths identified");
      }
    }
  }
}

/** 获取controller中所有方法的url,由子类实现,典型的模板模式 **/
protected abstract String[] determineUrlsForHandler(String beanName);


determineUrlsForHandler(String beanName)方法的作用是获取每个controller中的url,不同的子类有不同的实现,这是一个典型的模板设计模式.


因为开发中用的最多的就是用注解来配置controller中的url。DefaultAnnotationHandlerMapping是AbstractDetectingUrlHandlerMapping的子类,处理注解形式的url映射.


所以我们这里以DefaultAnnotationHandlerMapping来进行分析.我们看DefaultAnnotationHandlerMapping是如何查beanName上所有映射的url.


/**
* 获取controller中所有的url
*/

protected String[] determineUrlsForHandler(String beanName) {
  // 获取ApplicationContext容器
  ApplicationContext context = getApplicationContext();
  
  //从容器中获取controller
  Class handlerType = context.getType(beanName);
  
  // 获取controller上的@RequestMapping注解
  RequestMapping mapping = context.findAnnotationOnBean(beanName, RequestMapping.class);
  if (mapping != null) { // controller上有注解
    this.cachedMappings.put(handlerType, mapping);
    
    // 返回结果集

    Set<String> urls = new LinkedHashSet<String>();
    
    // controller的映射url

    String[] typeLevelPatterns = mapping.value();
    if (typeLevelPatterns.length > 0) { // url>0
      
      // 获取controller中所有方法及方法的映射url

      String[] methodLevelPatterns = determineUrlsForHandlerMethods(handlerType, true);
      for (String typeLevelPattern : typeLevelPatterns) {
        if (!typeLevelPattern.startsWith("/")) {
          typeLevelPattern = "/" + typeLevelPattern;
        }
        boolean hasEmptyMethodLevelMappings = false;
        for (String methodLevelPattern : methodLevelPatterns) {
          if (methodLevelPattern == null) {
            hasEmptyMethodLevelMappings = true;
          }
          else {
            // controller的映射url+方法映射的url
            String combinedPattern = getPathMatcher().combine(typeLevelPattern, methodLevelPattern);
            // 保存到set集合中
            addUrlsForPath(urls, combinedPattern);
          }
        }
        if (hasEmptyMethodLevelMappings || org.springframework.web.servlet.mvc.Controller.class.isAssignableFrom(handlerType)) {
          addUrlsForPath(urls, typeLevelPattern);
        }
      }
      // 以数组形式返回controller上的所有url
      return StringUtils.toStringArray(urls);
    }
    else {
      // controller上的@RequestMapping映射url为空串,直接找方法的映射url
      return determineUrlsForHandlerMethods(handlerType, false);
    }
  } // controller上没@RequestMapping注解
  else if (AnnotationUtils.findAnnotation(handlerType, Controller.class) != null) {
    // 获取controller中方法上的映射url
    return determineUrlsForHandlerMethods(handlerType, false);
  }
  else {
    return null;
}
}


到这里HandlerMapping组件就已经建立所有url和controller的对应关系。


第二步、根据访问url找到对应controller中处理请求的方法.

  下面我们开始分析第二个步骤,第二个步骤是由请求触发的,所以入口为DispatcherServlet.


DispatcherServlet的核心方法为doService(),doService()中的核心逻辑由doDispatch()实现,我们查看doDispatch()的源代码.


/** 中央控制器,控制请求的转发 **/
protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
  HttpServletRequest processedRequest = request;
  HandlerExecutionChain mappedHandler = null;
  int interceptorIndex = -1;

  try {
    ModelAndView mv;
    boolean errorView = false;
    try {
      // 1.检查是否是文件上传的请求
      processedRequest = checkMultipart(request);

      // 2.取得处理当前请求的controller,这里也称为hanlder,处理器,第一个步骤的意义就在这里体现了.这里并不是直接返回controller,而是返回的HandlerExecutionChain请求处理器链对象,该对象封装了handler和interceptors.
      mappedHandler = getHandler(processedRequest, false);
      // 如果handler为空,则返回404
      if (mappedHandler == null || mappedHandler.getHandler() == null) {
        noHandlerFound(processedRequest, response);
        return;
      }
      //3. 获取处理request的处理器适配器handler adapter
      HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler());
      // 处理 last-modified 请求头
      String method = request.getMethod();
      boolean isGet = "GET".equals(method);
      if (isGet || "HEAD".equals(method)) {
        long lastModified = ha.getLastModified(request, mappedHandler.getHandler());
        if (logger.isDebugEnabled()) {
          String requestUri = urlPathHelper.getRequestUri(request);
          logger.debug("Last-Modified value for [" + requestUri + "] is: " + lastModified);
        }
        if (new ServletWebRequest(request, response).checkNotModified(lastModified) && isGet) {
          return;
        }
      }

      // 4.拦截器的预处理方法
      HandlerInterceptor[] interceptors = mappedHandler.getInterceptors();
      if (interceptors != null) {
        for (int i = 0; i < interceptors.length; i++) {
          HandlerInterceptor interceptor = interceptors[i];
          if (!interceptor.preHandle(processedRequest, response, mappedHandler.getHandler())) {
            triggerAfterCompletion(mappedHandler, interceptorIndex, processedRequest, response, null);
            return;
          }
          interceptorIndex = i;
        }
      }

      // 5.实际的处理器处理请求,返回结果视图对象
      mv = ha.handle(processedRequest, response, mappedHandler.getHandler());

      // 结果视图对象的处理
      if (mv != null && !mv.hasView()) {
        mv.setViewName(getDefaultViewName(request));
      }

      // 6.拦截器的后处理方法
      if (interceptors != null) {
        for (int i = interceptors.length - 1; i >= 0; i--) {
          HandlerInterceptor interceptor = interceptors[i];
          interceptor.postHandle(processedRequest, response, mappedHandler.getHandler(), mv);
        }
      }
    }
    catch (ModelAndViewDefiningException ex) {
      logger.debug("ModelAndViewDefiningException encountered", ex);
      mv = ex.getModelAndView();
    }
    catch (Exception ex) {
      Object handler = (mappedHandler != null ? mappedHandler.getHandler() : null);
      mv = processHandlerException(processedRequest, response, handler, ex);
      errorView = (mv != null);
    }


    if (mv != null && !mv.wasCleared()) {
      render(mv, processedRequest, response);
      if (errorView) {
        WebUtils.clearErrorRequestAttributes(request);
      }
    }
    else {
      if (logger.isDebugEnabled()) {
        logger.debug("Null ModelAndView returned to DispatcherServlet with name '" + getServletName() + "': assuming HandlerAdapter completed request handling");
      }
    }

    // 请求成功响应之后的方法
    triggerAfterCompletion(mappedHandler, interceptorIndex, processedRequest, response, null);
  }
}


第2步:getHandler(processedRequest)方法实际上就是从HandlerMapping中找到url和controller的对应关系.这也就是第一个步骤:建立Map 的意义.


我们知道,最终处理request的是controller中的方法,我们现在只是知道了controller,还要进一步确认controller中处理request的方法.


由于下面的步骤和第三个步骤关系更加紧密,直接转到第三个步骤.



第三步、反射调用处理请求的方法,返回结果视图

  上面的方法中,第2步其实就是从第一个步骤中的Map 中取得controller,然后经过拦截器的预处理方法,到最核心的部分--第5步调用controller的方法处理请求.


在第2步中我们可以知道处理request的controller,第5步就是要根据url确定controller中处理请求的方法,然后通过反射获取该方法上的注解和参数,解析方法和参数上的注解,最后反射调用方法获取ModelAndView结果视图。


因为上面采用注解url形式说明的,所以我们这里继续以注解处理器适配器来说明.


第5步调用的就是AnnotationMethodHandlerAdapter的handle().handle()中的核心逻辑由invokeHandlerMethod(request, response, handler)实现。

/** 获取处理请求的方法,执行并返回结果视图 **/
protected ModelAndView invokeHandlerMethod(HttpServletRequest request, HttpServletResponse response, Object handler)
 throws Exception {
  // 1.获取方法解析器
  ServletHandlerMethodResolver methodResolver = getMethodResolver(handler);
  // 2.解析request中的url,获取处理request的方法
  Method handlerMethod = methodResolver.resolveHandlerMethod(request);
  // 3.方法调用器
  ServletHandlerMethodInvoker methodInvoker = new ServletHandlerMethodInvoker(methodResolver);
  ServletWebRequest webRequest = new ServletWebRequest(request, response);
  ExtendedModelMap implicitModel = new BindingAwareModelMap();
  // 4.执行方法
  Object result = methodInvoker.invokeHandlerMethod(handlerMethod, handler, webRequest, implicitModel);
  // 5.封装结果视图
  ModelAndView mav =
  methodInvoker.getModelAndView(handlerMethod, handler.getClass(), result, implicitModel, webRequest);
  methodInvoker.updateModelAttributes(handler, (mav != null ? mav.getModel() : null), implicitModel, webRequest);
  return mav;
}



这一部分的核心就在2和4了.


先看第2步,通过request找controller的处理方法.实际上就是拼接controller的url和方法的url,与request的url进行匹配,找到匹配的方法.


/** 根据url获取处理请求的方法 **/
public Method resolveHandlerMethod(HttpServletRequest request) throws ServletException {
  // 如果请求url为,localhost:8080/springmvc/helloWorldController/say.action, 则lookupPath=helloWorldController/say.action
  String lookupPath = urlPathHelper.getLookupPathForRequest(request);
  Comparator<String> pathComparator = pathMatcher.getPatternComparator(lookupPath);
  Map targetHandlerMethods =  new LinkedHashMap ();
  Set< String> allowedMethods =  new LinkedHashSet< String>( 7);
  String resolvedMethodName =  null;
  // 遍历controller上的所有方法,获取url匹配的方法
  for (Method handlerMethod : getHandlerMethods()) {
    RequestSpecificMappingInfo mappingInfo =  new RequestSpecificMappingInfo( this.mappings.get(handlerMethod));
    boolean match =