关于java:SpringMVC到底是如何处理请求的

40次阅读

共计 14988 个字符,预计需要花费 38 分钟才能阅读完成。

很多人会用 SpringMVC,但对它的解决申请的形式并不分明,当咱们学习一个常识的时候,理解它会让咱们更好地应用它,上面咱们来看看 SpringMVC 是如何解决申请的。

申请流程的形式

先上图:

Spring MVC 框架也是一个基于申请驱动的 Web 框架,并且应用了前端控制器模式(是用来提供一个集中的申请解决机制,所有的申请都将由一个繁多的处理程序解决来进行设计,再依据申请映射规定分发给相应的页面控制器(动作 / 处理器)进行解决。首先让咱们整体看一下 Spring MVC 解决申请的流程:

  1. 首先用户发送申请,申请被 SpringMVC 前端控制器(DispatherServlet)捕捉;
  2. 前端控制器(DispatherServlet)对申请 URL 解析获取申请 URI,依据 URI,调用 HandlerMapping;
  3. 前端控制器(DispatherServlet)取得返回的 HandlerExecutionChain(包含 Handler 对象以及 Handler 对象对应的拦截器);
  4. DispatcherServlet 依据取得的 HandlerExecutionChain,抉择一个适合的 HandlerAdapter。(附注:如果胜利取得 HandlerAdapter 后,此时将开始执行拦截器的 preHandler(…) 办法);
  5. HandlerAdapter 依据申请的 Handler 适配并执行对应的 Handler;HandlerAdapter 提取 Request 中的模型数据,填充 Handler 入参,开始执行 Handler(Controller)。在填充 Handler 的入参过程中,依据配置,Spring 将做一些额定的工作:

    HttpMessageConveter:将申请音讯(如 Json、xml 等数据)转换成一个对象,将对象转换为指定的响应信息;

    数据转换:对申请音讯进行数据转换。如 String 转换成 Integer、Double 等;

    数据格式化:如将字符串转换成格式化数字或格式化日期等;

    数据验证:验证数据的有效性(长度、格局等),验证后果存储到 BindingResult 或 Error 中);

  6. Handler 执行结束,返回一个 ModelAndView(即模型和视图)给 HandlerAdaptor;
  7. HandlerAdaptor 适配器将执行后果 ModelAndView 返回给前端控制器;
  8. 前端控制器接收到 ModelAndView 后,申请对应的视图解析器;
  9. 视图解析器解析 ModelAndView 后返回对应 View;
  10. 渲染视图并返回渲染后的视图给前端控制器;
  11. 最终前端控制器将渲染后的页面响应给用户或客户端。

案例实操

SpringMVC 申请执行源码解读

对于 SpringMVC 我的项目所有的申请入口(动态资源除外)这里都是从 web.xml 文件配置的前端控制器 DispatcherServlet 开始:

<!-- servlet 申请散发器 -->
<servlet>
  <servlet-name>springMvc</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <init-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:servlet-context.xml</param-value>
  </init-param>
  <!-- 示意启动容器时初始化该 Servlet -->
  <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
  <servlet-name>springMvc</servlet-name>
  <!-- 这是拦挡申请, / 代表拦挡所有申请, 拦挡所有.do 申请 -->
  <url-pattern>/</url-pattern>
</servlet-mapping> 

DispatcherServlet UML 继承关系图如下:

这里关注蓝线局部继承构造:DispatcherServlet–>FrameworkServlet–>HttpServletBean–>HttpServlet–>GenericServlet–>Servlet,对于申请外围时序图如下:

对于 web 申请的解决,大家都晓得是通过继承 HttpServlet 重写其 service 办法,这里关上 DispatcherServlet 源码发现这里并没有看到咱们要找的 service 办法,此时到父类 FrameworkServlet 查找如下:能够看到父类重写 HttpServlet service 办法。

FrameworkServlet#service

/**
 * Override the parent class implementation in order to intercept PATCH requests.
 */
@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {HttpMethod httpMethod = HttpMethod.resolve(request.getMethod());
   if (httpMethod == HttpMethod.PATCH || httpMethod == null) {processRequest(request, response);
   }
   else {super.service(request, response);
   }
} 

从源码剖析来看当申请办法为 patch 申请或者为 null 时执行 processRequest0 办法,其余状况则调用父类 service 办法,大家都晓得 SpringMVC 申请大多申请是 get|post 申请为主,此时持续向上查看 FrameworkServlet 父类 HttpServletBean(抽象类继承 HttpServlet 并未重写 service 办法,所以向上持续寻找 )–> HttpServlet service 办法:

HttpServlet#service

 @Override
    public void service(ServletRequest req, ServletResponse res)
        throws ServletException, IOException
    {
        HttpServletRequest  request;
        HttpServletResponse response;
        
        if (!(req instanceof HttpServletRequest &&
                res instanceof HttpServletResponse)) {throw new ServletException("non-HTTP request or response");
        }

        request = (HttpServletRequest) req;
        response = (HttpServletResponse) res;

        service(request, response);
    }
}

protected void service(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException
    {String method = req.getMethod();

        if (method.equals(METHOD_GET)) {long lastModified = getLastModified(req);
            if (lastModified == -1) {
                // servlet doesn't support if-modified-since, no reason
                // to go through further expensive logic
                doGet(req, resp);
            } else {long ifModifiedSince = req.getDateHeader(HEADER_IFMODSINCE);
                if (ifModifiedSince < lastModified) {// If the servlet mod time is later, call doGet()
                    // Round down to the nearest second for a proper compare
                    // A ifModifiedSince of -1 will always be less
                    maybeSetLastModified(resp, lastModified);
                    doGet(req, resp);
                } else {resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
                }
            }

        } else if (method.equals(METHOD_HEAD)) {long lastModified = getLastModified(req);
            maybeSetLastModified(resp, lastModified);
            doHead(req, resp);

        } else if (method.equals(METHOD_POST)) {doPost(req, resp);
            
        } else if (method.equals(METHOD_PUT)) {doPut(req, resp);
            
        } else if (method.equals(METHOD_DELETE)) {doDelete(req, resp);
            
        } else if (method.equals(METHOD_OPTIONS)) {doOptions(req,resp);
            
        } else if (method.equals(METHOD_TRACE)) {doTrace(req,resp);
            
        } else {
            //
            // Note that this means NO servlet supports whatever
            // method was requested, anywhere on this server.
            //

            String errMsg = lStrings.getString("http.method_not_implemented");
            Object[] errArgs = new Object[1];
            errArgs[0] = method;
            errMsg = MessageFormat.format(errMsg, errArgs);
            
            resp.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED, errMsg);
        }
    } 

能够看到 HttpServlet service 进行了重载,依据不同的申请类型而后调用不同解决办法,这里以 get 申请为例,当申请办法为 get 申请时在重载 service 办法中调用 doGet 办法进行解决,这里须要特地留神的是:HttpServlet 存在 doGet 办法实现,然而在继承的子类中也存在 doGet 办法实现,到底调用哪个办法?很显著调用子类的 doGet 办法(面向对象多态思维!!!)从继承 UML 关系图上看,最外层子类实现 doGet 办法的为 FrameworkServlet:

FrameworkServlet#doGet&processRequest

@Override
protected final void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {processRequest(request, response);
}

    protected final void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        // 零碎计时开始工夫
        long startTime = System.currentTimeMillis();
        Throwable failureCause = null;
        // 国际化
        LocaleContext previousLocaleContext = LocaleContextHolder.getLocaleContext();
        LocaleContext localeContext = buildLocaleContext(request);
        // 构建 ServletRequestAttributes 对象
        RequestAttributes previousAttributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes requestAttributes = buildRequestAttributes(request, response, previousAttributes);
        // 异步治理
        WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
        asyncManager.registerCallableInterceptor(FrameworkServlet.class.getName(), new RequestBindingInterceptor());
        // 初始化 ContextHolders
        initContextHolders(request, localeContext, requestAttributes);

        try {doService(request, response);
        }
        catch (ServletException | IOException ex) {
            failureCause = ex;
            throw ex;
        }
        catch (Throwable ex) {
            failureCause = ex;
            throw new NestedServletException("Request processing failed", ex);
        }

        finally {
             // 复原原来的 LocaleContext 和 ServiceRequestAttributes 到 LocaleContextHolder 和 RequestContextHolder,防止影响 Servlet 以外的解决,如 Filter
            resetContextHolders(request, previousLocaleContext, previousAttributes);
            if (requestAttributes != null) {requestAttributes.requestCompleted();
            }
            logResult(request, response, failureCause, asyncManager);
            // 公布 ServletRequestHandlerEvent 音讯,这个申请是否执行胜利都会公布音讯的
            publishRequestHandledEvent(request, response, startTime, failureCause);
        }
    }

// initContextHolders(request, localeContext, requestAttributes);
    private void initContextHolders(HttpServletRequest request,
            @Nullable LocaleContext localeContext, @Nullable RequestAttributes requestAttributes) {if (localeContext != null) {LocaleContextHolder.setLocaleContext(localeContext, this.threadContextInheritable);
        }
        if (requestAttributes != null) {RequestContextHolder.setRequestAttributes(requestAttributes, this.threadContextInheritable);
        }
    } 

该办法大略做了这几件事:国际化的设置,创立 ServletRequestAttributes 对象,初始化上下文 holders(行将 Request 对象放入到线程上下文中,如后续想要在办法中获取 request、response 对象此时能够通过调用 LocaleContextHolder 对应办法即可),而后调用 doService 办法。对于 doService 办法,FrameworkServlet 类并未提供实现,该办法由 DispatcherServlet 子类实现:

DispatcherServlet#doService

DispatcherServlet 外面执行解决的入口办法是 doService,因为这个类继承于 FrameworkServlet 类,重写了 doService() 办法:

@Override
protected void doService(HttpServletRequest request, HttpServletResponse response) throws Exception {logRequest(request);

   // Keep a snapshot of the request attributes in case of an include,
   // to be able to restore the original attributes after the include.
   Map<String, Object> attributesSnapshot = null;
   if (WebUtils.isIncludeRequest(request)) {attributesSnapshot = new HashMap<>();
      Enumeration<?> attrNames = request.getAttributeNames();
      while (attrNames.hasMoreElements()) {String attrName = (String) attrNames.nextElement();
         if (this.cleanupAfterInclude || attrName.startsWith(DEFAULT_STRATEGIES_PREFIX)) {attributesSnapshot.put(attrName, request.getAttribute(attrName));
         }
      }
   }

    //Spring 上下文
   request.setAttribute(WEB_APPLICATION_CONTEXT_ATTRIBUTE, getWebApplicationContext());
    // 国际化解析器
   request.setAttribute(LOCALE_RESOLVER_ATTRIBUTE, this.localeResolver);
    // 主题解析器
   request.setAttribute(THEME_RESOLVER_ATTRIBUTE, this.themeResolver);
    // 主题
   request.setAttribute(THEME_SOURCE_ATTRIBUTE, getThemeSource());

    // 重定向的数据 
   if (this.flashMapManager != null) {FlashMap inputFlashMap = this.flashMapManager.retrieveAndUpdate(request, response);
      if (inputFlashMap != null) {request.setAttribute(INPUT_FLASH_MAP_ATTRIBUTE, Collections.unmodifiableMap(inputFlashMap));
      }
      request.setAttribute(OUTPUT_FLASH_MAP_ATTRIBUTE, new FlashMap());
      request.setAttribute(FLASH_MAP_MANAGER_ATTRIBUTE, this.flashMapManager);
   }

   try {
      //request 设置完相干的属性做真正的申请解决
      doDispatch(request, response);
   }
   finally {if (!WebAsyncUtils.getAsyncManager(request).isConcurrentHandlingStarted()) {
         // Restore the original attribute snapshot, in case of an include.
         if (attributesSnapshot != null) {restoreAttributesAfterInclude(request, attributesSnapshot);
         }
      }
   }
} 

整个办法看下来解决的操作有:解决 include 标签的申请,将上下文放到 request 的属性中,将国际化解析器放到 request 的属性中,将主题解析器放到 request 属性中,将主题放到 request 的属性中,解决重定向的申请数据最初调用 doDispatch 这个外围的办法对申请进行解决:

DispatcherServlet#doDispatch

该办法是在 doService 办法中调用的,从底层设计了整个申请的解决流程:

  • 依据 request 找到 Handler
  • 依据 Handler 找到对应的 HandlerAdapter
  • 用 HandlerAdapter 解决 Handler
  • 调用 processDispatchResult 办法解决下面之后的后果(蕴含 View 渲染并输入给用户)
protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
   HttpServletRequest processedRequest = request;
   HandlerExecutionChain mappedHandler = null;
   boolean multipartRequestParsed = false;
   WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);

   try {
      ModelAndView mv = null;
      Exception dispatchException = null;

      try {
          // 校验是否为上传申请 是上传申请执行解析 否则返回 request
         processedRequest = checkMultipart(request);
         multipartRequestParsed = (processedRequest != request);

         // 依据拜访的 Handler 返回指定对应的 HandlerExecutionChain 对象 这里从 HandlerMapping 汇合中查找 HandlerExecutionChain 对象蕴含 Handler 与拦截器 HandlerInterceptor 列表
         mappedHandler = getHandler(processedRequest);
         if (mappedHandler == null) {noHandlerFound(processedRequest, response);
            return;
         }

         // 依据失去的 Handler 获取对应的 HandlerAdaptor 对象
         HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler());

         // 解决 GET、HEAD 申请的 Last-Modified
         String method = request.getMethod();
         boolean isGet = "GET".equals(method);
         if (isGet || "HEAD".equals(method)) {long lastModified = ha.getLastModified(request, mappedHandler.getHandler());
            // 当数据没有更改时,就间接返回上次的数据,提高效率
             if (new ServletWebRequest(request, response).checkNotModified(lastModified) && isGet) {return;}
         }

         // 执行 Interceptor 的 preHandle 
         if (!mappedHandler.applyPreHandle(processedRequest, response)) {return;}

         // 执行 Handler 返回 ModelAndView
         mv = ha.handle(processedRequest, response, mappedHandler.getHandler());

          // 如果须要异步解决,间接返回
         if (asyncManager.isConcurrentHandlingStarted()) {return;}

         // 当 view 为空时,依据 request 设置默认 view,如 Handler 返回值为 void
         applyDefaultViewName(processedRequest, mv);
         // 执行相应 Interceptor 的 postHandle 
         mappedHandler.applyPostHandle(processedRequest, response, mv);
      }
      catch (Exception ex) {dispatchException = ex;}
      catch (Throwable err) {
         // As of 4.3, we're processing Errors thrown from handler methods as well,
         // making them available for @ExceptionHandler methods and other scenarios.
         dispatchException = new NestedServletException("Handler dispatch failed", err);
      }
       // 解决返回后果,包含解决异样、渲染页面,收回实现告诉触发 Interceptor 的 afterCompletion
      processDispatchResult(processedRequest, response, mappedHandler, mv, dispatchException);
   }
   catch (Exception ex) {triggerAfterCompletion(processedRequest, response, mappedHandler, ex);
   }
   catch (Throwable err) {
      triggerAfterCompletion(processedRequest, response, mappedHandler,
            new NestedServletException("Handler processing failed", err));
   }
   finally {if (asyncManager.isConcurrentHandlingStarted()) {
         // Instead of postHandle and afterCompletion
         if (mappedHandler != null) {mappedHandler.applyAfterConcurrentHandlingStarted(processedRequest, response);
         }
      }
      else {
         // Clean up any resources used by a multipart request.
         if (multipartRequestParsed) {cleanupMultipart(processedRequest);
         }
      }
   }
} 
  1. doDispatcher 首先查看是不是上传申请,如果是则将 request 转换为 MultipartHttpServletRequest,并将 multipartRequestParsed 标记设置为 true;
  2. 通过 getHandler 获取 Handler 处理器链 HandlerExecutionChain;
  3. 解决 GET、HEAD 申请的 Last-Modified,这里次要判断 Last-Modified 值是否被批改来解决决定是否采纳缓存数据;
  4. 接下来顺次调用相应的 Interceptor 的 preHandle,执行拦截器拦挡操作;
  5. 拦截器 preHandle 办法执行后,此时开始通过 HandlerAdapter 适配对应的 Handler 执行(这里才是真正要执行的 Controller 办法),Handler 解决完申请后,如果须要异步解决则间接返回,如果不须要异步解决,当 view 为空时,设置默认 view,而后执行相应的 Interceptor 的 postHandle。
  • Handler:处理器,他间接对应着 MVC 中的 C,也就是 Controller 层,它的具体表现形式有很多,能够是类,也能够是办法(通常以办法居多),因为它的定义是 Object,咱们在办法中标注的 @RequestMapping 的所有办法都能够看成一个 Handler,只有能够理论解决申请的都能够看成 Handler。
  • HandlerMapping:用来查找 Handler,在 SpringMVC 中会解决很多申请,每一个申请都须要一个 Handler 来解决,具体承受到申请后须要哪一个 Handler 来解决,此时通过 HandlerMapping 来实现查找。
  • HandlerAdapter:适配器,不同的 Handler 须要找到不同 HandlerAdapter 来调用 Handler。就如工厂里须要应用工具,工人(HandlerAdapter)应用工具(Handler)实现工作,而 HandlerMapping 用于依据须要实现的工作来找到相应的工具。

DispatcherServlet#processDispatchResult

processDispatchResult 办法次要用来解决后面返回的后果,其中包含解决异样、渲染页面、触发 Interceptor 的 afterCompletion 办法三局部内容,解决的异样是在解决申请 doDispatch 办法的过程中产生。

private void processDispatchResult(HttpServletRequest request, HttpServletResponse response,
      @Nullable HandlerExecutionChain mappedHandler, @Nullable ModelAndView mv,
      @Nullable Exception exception) throws Exception {

   boolean errorView = false;
   // 如果申请过程中有异样抛出则解决异样
   if (exception != null) {if (exception instanceof ModelAndViewDefiningException) {logger.debug("ModelAndViewDefiningException encountered", exception);
         mv = ((ModelAndViewDefiningException) exception).getModelAndView();}
      else {Object handler = (mappedHandler != null ? mappedHandler.getHandler() : null);
         mv = processHandlerException(request, response, handler, exception);
         errorView = (mv != null);
      }
   }

   // 执行页面渲染操作
   if (mv != null && !mv.wasCleared()) {render(mv, request, response);
      if (errorView) {WebUtils.clearErrorRequestAttributes(request);
      }
   }
   else {if (logger.isTraceEnabled()) {logger.trace("No view rendering, null ModelAndView returned.");
      }
   }

   if (WebAsyncUtils.getAsyncManager(request).isConcurrentHandlingStarted()) {
      // Concurrent handling started during a forward
      return;
   }

   // Handler 申请解决完,触发 Interceptor 的 afterCompletion
   if (mappedHandler != null) {// Exception (if any) is already handled..
      mappedHandler.triggerAfterCompletion(request, response, null);
   }
} 

render 视图渲染:

protected void render(ModelAndView mv, HttpServletRequest request, HttpServletResponse response) throws Exception {
   // Determine locale for request and apply it to the response.
   Locale locale =
         (this.localeResolver != null ? this.localeResolver.resolveLocale(request) : request.getLocale());
   response.setLocale(locale);

   View view;
   String viewName = mv.getViewName();
   if (viewName != null) {
      // We need to resolve the view name.
      view = resolveViewName(viewName, mv.getModelInternal(), locale, request);
      if (view == null) {throw new ServletException("Could not resolve view with name'" + mv.getViewName() +
               "'in servlet with name'" + getServletName() + "'");
      }
   }
   else {
      // No need to lookup: the ModelAndView object contains the actual View object.
      view = mv.getView();
      if (view == null) {throw new ServletException("ModelAndView [" + mv + "] neither contains a view name nor a" +
               "View object in servlet with name'" + getServletName() + "'");
      }
   }

 
   if (logger.isTraceEnabled()) {logger.trace("Rendering view [" + view + "]");
   }
   try {if (mv.getStatus() != null) {response.setStatus(mv.getStatus().value());
      }
       // 渲染页面解决
      view.render(mv.getModelInternal(), request, response);
   }
   catch (Exception ex) {if (logger.isDebugEnabled()) {logger.debug("Error rendering view [" + view + "]", ex);
      }
      throw ex;
   }
} 

明天咱们来理解了一下 SpringMVC 框架中 MVC 核心思想,SpringMVC 外部申请流程剖析以及源码级别代码解读,让大家真正可能从底层级别了解整个框架执行原貌,最初以一张图来总结明天的源码剖析执行流程。

扩大~MVC

模型 - 视图 - 控制器(MVC)是一个家喻户晓的以设计界面应用程序为根底的设计思维。它次要通过拆散模型、视图及控制器在应用程序中的角色将业务逻辑从界面中解耦。通常,模型负责封装应用程序数据在视图层展现。视图仅仅只是展现这些数据,不蕴含任何业务逻辑。控制器负责接管来自用户的申请,并调用后盾服务(service 或者 dao)来解决业务逻辑。解决后,后盾业务层可能会返回了一些数据在视图层展现。控制器收集这些数据及筹备模型在视图层展现。MVC 模式的核心思想是将业务逻辑从界面中分离出来,容许它们独自扭转而不会相互影响。

写在结尾:感激大家看到完结

感兴趣的能够点赞评论

关注公众号:隆冬的代码

你须要的我都有~

正文完
 0