栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

SpringBoot、Spring、SpringMVC原理梳理

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SpringBoot、Spring、SpringMVC原理梳理

SpringBoot、Spring、SpringMVC原理梳理

文章目录
  • SpringBoot、Spring、SpringMVC原理梳理
    • Spring、SpringMVC、SpringBoot三者的关系:
          • Spring和SpringMVC:
          • SpringBoot、Spring:
    • SpringMVC的DispatchServlet解析
        • DispatchServlet初始化:
          • initServletBean
          • initWebApplicationContext();
            • createWebApplicationContext:
            • 首先第一步:获取当前配置文件的信息:
            • 第二步:设置环境wac.setEnvironment(getEnvironment());
            • 第三步: wac.setParent(parent);
            • 第四步: getContextConfigLocation()和创建;
            • 第五步:configureAndRefreshWebApplicationContext(wac);
            • 第六步:返回初始化完毕的webApplicationContext;
            • 回到initWebApplicationContext:
            • DispatchServlet实现onRefresh(wac);
          • 总结:
        • DispatcherServlet调用组件处理请求
          • a>processRequest()
          • b>doService()
          • c>doDispatch()
          • d>processDispatchResult()
      • SpringMVC的执行流程

Spring、SpringMVC、SpringBoot三者的关系:

​

Spring和SpringMVC:

​ springmvc和spring都是容器,容器就是管理对象的地方,例如Tomcat,就是管理servlet对象的,而springMVC容器和spring容器,就是管理bean对象的地方,再说的直白点,springmvc就是管理controller对象的容器,spring就是管理service和dao的容器。所以在springmvc的配置文件里配置的扫描路径就是controller的路径,而spring的配置文件里自然配的就是service和dao的路径。

​ 其次, spring容器和springmvc容器的关系是父子容器的关系。spring容器是父容器,springmvc是子容器。在子容器里可以访问父容器里的对象,但是在父容器里不可以访问子容器的对象,说的通俗点就是,在controller里可以访问service对象,但是在service里不可以访问controller对象

​ 所以这么看的话,所有的bean,都是被spring或者springmvc容器管理的,他们可以直接注入。然后springMVC的拦截器也是springmvc容器管理的,所以在springmvc的拦截器里,可以直接注入bean对象。

​ web容器是管理servlet,以及监听器(Listener)和过滤器(Filter)的。这些都是在web容器的掌控范围里。但他们不在spring和springmvc的掌控范围里。因此,我们无法在这些类中直接使用Spring注解的方式来注入我们需要的对象,是无效的,web容器是无法识别的。

​ 而无法通过注解方式获取我们所需要的bean:则需要通过加载注解文件的方式。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-wNwE1in6-1652669089203)(C:UserszhangxyDesktop笔记springSpringBoot、Spring、SpringMVC原理梳理.assetsimage-20220513220136844.png)]

​ 注意:以上代码有一个前提,那就是servlet容器在实例化ConfigListener并调用其方法之前,要确保spring容器已经初始化完毕!而spring容器的初始化也是由Listener(ContextLoaderListener)完成,因此只需在web.xml中先配置初始化spring容器的Listener,然后在配置自己的Listener。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-NhetuXUu-1652669089204)(C:UserszhangxyDesktop笔记springSpringBoot、Spring、SpringMVC原理梳理.assetsimage-20220513220348567.png)]

​ web容器中有servlet容器,spring项目部署后存在spring容器和springmvc容器。其中spring控制service层和dao层的bean对象。springmvc容器控制controller层bean对象。servlet容器控制servlet对象。项目启动是,首先 servlet初始化,初始化过程中通过web.xml中spring的配置加载spring配置,初始化spring容器和springmvc容器。待容器加载完成。servlet初始化完成,则完成启动。
​ HTTP请求到达web容器后,会到达Servlet容器,容器通过分发器分发到具体的spring的Controller层。执行业务操作后返回结果。

​ Tomcat在启动时给每个Web应用创建一个全局的上下文环境,这个上下文就是ServletContext,其为后面的Spring容器提供宿主环境。

​ Tomcat在启动过程中触发容器初始化事件,Spring的ContextLoaderListener会监听到这个事件,它的contextInitialized方法会被调用,在这个方法中,Spring会初始化全局的Spring根容器,这个就是Spring的IoC容器,IoC容器初始化完毕后,Spring将其存储到ServletContext中,便于以后来获取。

​ Tomcat在启动过程中还会扫描Servlet,一个Web应用中的Servlet可以有多个,以SpringMVC中的DispatcherServlet为例,这个Servlet实际上是一个标准的前端控制器,用以转发、匹配、处理每个Servlet请求。

​ Servlet一般会延迟加载,当第一个请求达到时,Tomcat&Jetty发现DispatcherServlet还没有被实例化,就调用DispatcherServlet的init方法,DispatcherServlet在初始化的时候会建立自己的容器,叫做SpringMVC 容器,用来持有Spring MVC相关的Bean。

​ 同时,Spring MVC还会通过ServletContext拿到Spring根容器,并将Spring根容器设为SpringMVC容器的父容器,请注意,Spring MVC容器可以访问父容器中的Bean,但是父容器不能访问子容器的Bean, 也就是说Spring根容器不能访问SpringMVC容器里的Bean。说的通俗点就是,在Controller里可以访问Service对象,但是在Service里不可以访问Controller对象。

SpringBoot、Spring:

​ SpringBoot:Spring框架的扩展,其设计目的是简单Spring初始搭建以及开发过程,采用约定大于配置的方式,大量减少配置文件的使用,即采用默认配置即可,如有特殊需求自定义配置即可,它的一些特点如下:

​ 1.快速创建Spring应用

​ 2.内嵌Tomcat、Jetty等容器

​ 3.提供"starter" poms来简化maven依赖的配置

​ 4.消除了之前spring的xml配置

SpringBoot与Spring框架的关系:

SpringBoot框架是Spring框架的一种扩展,基于Spring技术,简化开发提供starter依赖包、内嵌容器、消除xml;

SpringBoot与SpringMVC框架的关系:

SpingMVC是web应用MVC架构的一种实现,如果一个SpringBoot项目是web项目则可以使用SpringMVC模式开发。

SpringMVC的DispatchServlet解析 DispatchServlet初始化:

​ 所在类:org.springframework.web.servlet.FrameworkServlet

​ DispatchServlet本质上是一个Servlet,所以天然遵循Servlet的生命周期。所以宏观上是Servlet生命周期调度。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-mCPfRLgf-1652669089204)(C:UserszhangxyDesktop笔记springSpringBoot、Spring、SpringMVC原理梳理.assetsimage-20220513222309005.png)]

DispatchServlet如图中逐层继承,而GenericServlet则是实现了Servlet接口的方法。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-1520f4wb-1652669089205)(C:UserszhangxyDesktop笔记springSpringBoot、Spring、SpringMVC原理梳理.assetsimage-20220513225452059.png)]

initServletBean

​ 作为接口的Servlet创建之后调用实现类(GenericServlet)的init方法,之后HTTPSerlvet重写init方法。在init方法中调用initServletBean方法,该方法之后再FrameworkServlet中重写。

@Override
protected final void initServletBean() throws ServletException {
   getServletContext().log("Initializing Spring " + getClass().getSimpleName() + " '" + getServletName() + "'");
   if (logger.isInfoEnabled()) {
       //输出当前Servlet名称。
      logger.info("Initializing Servlet '" + getServletName() + "'");
   }
   long startTime = System.currentTimeMillis();

   try {t
       //初始化WebApplicationContext
      this.webApplicationContext = initWebApplicationContext();
      initFrameworkServlet();
   }
   catch (ServletException | RuntimeException ex) {
      logger.error("Context initialization failed", ex);
      throw ex;
   }

   if (logger.isDebugEnabled()) {
      String value = this.enableLoggingRequestDetails ?
            "shown which may lead to unsafe logging of potentially sensitive data" :
            "masked to prevent unsafe logging of potentially sensitive data";
      logger.debug("enableLoggingRequestDetails='" + this.enableLoggingRequestDetails +
            "': request parameters and headers will be " + value);
   }

   if (logger.isInfoEnabled()) {
      logger.info("Completed initialization in " + (System.currentTimeMillis() - startTime) + " ms");
   }
}
initWebApplicationContext();

在打印完当前Servlet的名称和获取系统当前时间之后就initWebApplicationContext进行WebApplicationContext的初始化:

protected WebApplicationContext initWebApplicationContext() {
   WebApplicationContext rootContext =
         WebApplicationContextUtils.getWebApplicationContext(getServletContext());
   WebApplicationContext wac = null;

   
   if (this.webApplicationContext != null) {
      // A context instance was injected at construction time -> use it
      wac = this.webApplicationContext;
      if (wac instanceof ConfigurableWebApplicationContext) {
         ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) wac;
         if (!cwac.isActive()) {
            // The context has not yet been refreshed -> provide services such as
            // setting the parent context, setting the application context id, etc
            if (cwac.getParent() == null) {
               // The context instance was injected without an explicit parent -> set
               // the root application context (if any; may be null) as the parent
               cwac.setParent(rootContext);
            }
            configureAndRefreshWebApplicationContext(cwac);
         }
      }
   }
   if (wac == null) {
      // No context instance was injected at construction time -> see if one
      // has been registered in the servlet context. If one exists, it is assumed
      // that the parent context (if any) has already been set and that the
      // user has performed any initialization such as setting the context id
      wac = findWebApplicationContext();
   }
   if (wac == null) {
      // No context instance is defined for this servlet -> create a local one
      wac = createWebApplicationContext(rootContext);
   }

   if (!this.refreshEventReceived) {
      // Either the context is not a ConfigurableApplicationContext with refresh
      // support or the context injected at construction time had already been
      // refreshed -> trigger initial onRefresh manually here.
      synchronized (this.onRefreshMonitor) {
         onRefresh(wac);
      }
   }

   if (this.publishContext) {
      // Publish the context as a servlet context attribute.
      String attrName = getServletContextAttributeName();
      getServletContext().setAttribute(attrName, wac);
   }

   return wac;
}

​ Q:而在初始化时,疑问的是,既然在开始时定义了为空,那么为什么还要判断为空呢?而在什么情况WebApplicationContext不i会为空呢?

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-pq6HmeG2-1652669089205)(C:UserszhangxyDesktop笔记springSpringBoot、Spring、SpringMVC原理梳理.assetsimage-20220513231728596.png)]

Q:而在其为空null时首先的时寻找此时容器中是否有WebApplicationContext,那在什么情况下会有么,什么情况下会报错呢?

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Xf8DS3VQ-1652669089205)(C:UserszhangxyDesktop笔记springSpringBoot、Spring、SpringMVC原理梳理.assetsimage-20220513233404221.png)]

在做完上述两个步骤之后没有返回WebApplicationContext,则之后就会创建一个WebApplicationContext;

createWebApplicationContext:
protected WebApplicationContext createWebApplicationContext(@Nullable ApplicationContext parent) {
   Class contextClass = getContextClass();
   if (!ConfigurableWebApplicationContext.class.isAssignableFrom(contextClass)) {
      throw new ApplicationContextException(
            "Fatal initialization error in servlet with name '" + getServletName() +
            "': custom WebApplicationContext class [" + contextClass.getName() +
            "] is not of type ConfigurableWebApplicationContext");
   }
   ConfigurableWebApplicationContext wac =
         (ConfigurableWebApplicationContext) BeanUtils.instantiateClass(contextClass);

   wac.setEnvironment(getEnvironment());
   wac.setParent(parent);
   String configLocation = getContextConfigLocation();
   if (configLocation != null) {
      wac.setConfigLocation(configLocation);
   }
   configureAndRefreshWebApplicationContext(wac);

   return wac;
}
首先第一步:获取当前配置文件的信息:
    ConfigurableWebApplicationContext wac =
     (ConfigurableWebApplicationContext) BeanUtils.instantiateClass(contextClass);
     通过源码观察可知为什么配置文件的名称需要为application.xml,在XmlWebApplicationContext中就定义了这个配置文件的具体写法。ConfigurableWebApplicationContext中具有关闭和刷新的功能,通过反射创建这个对象

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-g11qRGFX-1652669089206)(C:UserszhangxyDesktop笔记springSpringBoot、Spring、SpringMVC原理梳理.assetsimage-20220513235026396.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-IolzfYGQ-1652669089206)(C:UserszhangxyDesktop笔记springSpringBoot、Spring、SpringMVC原理梳理.assetsimage-20220513235039104.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-uMA08pmi-1652669089207)(C:UserszhangxyDesktop笔记springSpringBoot、Spring、SpringMVC原理梳理.assetsimage-20220513235200122.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-w4E15XQ2-1652669089207)(C:UserszhangxyDesktop笔记springSpringBoot、Spring、SpringMVC原理梳理.assetsimage-20220513235211984.png)]

第二步:设置环境wac.setEnvironment(getEnvironment());
wac.setEnvironment(getEnvironment());

​ [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-km5SA7ex-1652669089208)(C:UserszhangxyDesktop笔记springSpringBoot、Spring、SpringMVC原理梳理.assetsimage-20220514160339829.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-wFoUpWFJ-1652669089208)(C:UserszhangxyDesktop笔记springSpringBoot、Spring、SpringMVC原理梳理.assetsimage-20220514160342366.png)]

​ 如果此时环境为空则创建StandardServletEnvironment;

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-QYALh8AX-1652669089208)(C:UserszhangxyDesktop笔记springSpringBoot、Spring、SpringMVC原理梳理.assetsimage-20220514160512082.png)]

第三步: wac.setParent(parent);

​ Spring和SpringMVC整合,二者都会创建IOC容器,这一步的目的是设置Spring的IOC容器为SpringMVC IOC容器的父容器。

第四步: getContextConfigLocation()和创建;

​ 获取本地上下文配置信息;如果没有的话就会进行创建。

​ wac.setConfigLocation(configLocation);

第五步:configureAndRefreshWebApplicationContext(wac);

​ 配置和刷新WebApplicationContext;

​

protected void configureAndRefreshWebApplicationContext(ConfigurableWebApplicationContext wac) {
   if (ObjectUtils.identityToString(wac).equals(wac.getId())) {
      // The application context id is still set to its original default value
      // -> assign a more useful id based on available information
      if (this.contextId != null) {
         wac.setId(this.contextId);
      }
      else {
         // Generate default id...
         wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX +
               ObjectUtils.getDisplayString(getServletContext().getContextPath()) + '/' + getServletName());
      }
   }

    //ServletContext是一个全局的储存信息的空间,服务器开始就存在,服务器关闭才释放。
    //https://www.w3cschool.cn/servlet/servlet-3ceg2p0t.html     ServletContext详解
    //WEB容器在启动时,它会为每个Web应用程序都创建一个对应的ServletContext,它代表当前Web应用,并且它被所有客户端共享。
   wac.setServletContext(getServletContext());
   //ServletConfig代表的是当前servlet在web.xml中的配置信息
   wac.setServletConfig(getServletConfig());
    //设置命名空间
   wac.setNamespace(getNamespace());
    //添加应用监听器
   wac.addApplicationListener(new SourceFilteringListener(wac, new ContextRefreshListener()));

   // The wac environment's #initPropertySources will be called in any case when the context
   // is refreshed; do it eagerly here to ensure servlet property sources are in place for
   // use in any post-processing or initialization that occurs below prior to #refresh
   ConfigurableEnvironment env = wac.getEnvironment();
   if (env instanceof ConfigurableWebEnvironment) {
      ((ConfigurableWebEnvironment) env).initPropertySources(getServletContext(), getServletConfig());
   }

   postProcessWebApplicationContext(wac);
   applyInitializers(wac);
   wac.refresh();
}
第六步:返回初始化完毕的webApplicationContext;

​ return wac;

回到initWebApplicationContext:

​ 在创建完webApplicationContext之后

if (!this.refreshEventReceived) {
   // Either the context is not a ConfigurableApplicationContext with refresh
   // support or the context injected at construction time had already been
   // refreshed -> trigger initial onRefresh manually here.
   synchronized (this.onRefreshMonitor) {
       
      onRefresh(wac);
      //需要DispatchServlet实现
     //	protected void onRefresh(ApplicationContext context) {
	// For subclasses: do nothing by default.
	//	}
   }
}

if (this.publishContext) {
   // Publish the context as a servlet context attribute.
    //获取ServletContext属性名
   String attrName = getServletContextAttributeName();
    //将webApplicationContext进行共享,以attrName为属性名,wac为属性
   getServletContext().setAttribute(attrName, wac);
}

return wac;
DispatchServlet实现onRefresh(wac);
@Override
protected void onRefresh(ApplicationContext context) {
   initStrategies(context);
}


protected void initStrategies(ApplicationContext context) {
    //初始化当前文件上传解析器
   initMultipartResolver(context);
   initLocaleResolver(context);
   initThemeResolver(context);
    //初始化请求和控制器方法创建映射关系
   initHandlerMappings(context);
    //调用控制器方法
   initHandlerAdapters(context);
    //初始化异常处理器
   initHandlerExceptionResolvers(context);
   initRequestToViewNameTranslator(context);
    //初始化视图解析器
   initViewResolvers(context);
   initFlashMapManager(context);
}
总结:

在此时,WebApplicationContext创建完毕,进入首页。

DispatcherServlet调用组件处理请求 a>processRequest()

FrameworkServlet重写HttpServlet中的service()和doXxx(),这些方法中调用了processRequest(request, response)

所在类:org.springframework.web.servlet.FrameworkServlet

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);

    RequestAttributes previousAttributes = RequestContextHolder.getRequestAttributes();
    ServletRequestAttributes requestAttributes = buildRequestAttributes(request, response, previousAttributes);

    WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
    asyncManager.registerCallableInterceptor(FrameworkServlet.class.getName(), new RequestBindingInterceptor());

    initContextHolders(request, localeContext, requestAttributes);

    try {
		// 执行服务,doService()是一个抽象方法,在DispatcherServlet中进行了重写
        doService(request, response);
    }
    catch (ServletException | IOException ex) {
        failureCause = ex;
        throw ex;
    }
    catch (Throwable ex) {
        failureCause = ex;
        throw new NestedServletException("Request processing failed", ex);
    }

    finally {
        resetContextHolders(request, previousLocaleContext, previousAttributes);
        if (requestAttributes != null) {
            requestAttributes.requestCompleted();
        }
        logResult(request, response, failureCause, asyncManager);
        publishRequestHandledEvent(request, response, startTime, failureCause);
    }
}
b>doService()

所在类:org.springframework.web.servlet.DispatcherServlet

@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 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));
            }
        }
    }

    // Make framework objects available to handlers and view objects.
    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);
    }

    RequestPath requestPath = null;
    if (this.parseRequestPath && !ServletRequestPathUtils.hasParsedRequestPath(request)) {
        requestPath = ServletRequestPathUtils.parseAndCache(request);
    }

    try {
        // 处理请求和响应
        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);
            }
        }
        if (requestPath != null) {
            ServletRequestPathUtils.clearParsedRequestPath(request);
        }
    }
}
c>doDispatch()

所在类:org.springframework.web.servlet.DispatcherServlet

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 {
            processedRequest = checkMultipart(request);
            multipartRequestParsed = (processedRequest != request);

            // Determine handler for the current request.
            
            mappedHandler = getHandler(processedRequest);
            if (mappedHandler == null) {
                noHandlerFound(processedRequest, response);
                return;
            }

            // Determine handler adapter for the current request.
           	// 通过控制器方法创建相应的处理器适配器,调用所对应的控制器方法
            HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler());

            // Process last-modified header, if supported by the handler.
            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;
                }
            }
			
            // 调用拦截器的preHandle()
            if (!mappedHandler.applyPreHandle(processedRequest, response)) {
                return;
            }

            // Actually invoke the handler.
            // 由处理器适配器调用具体的控制器方法,将获取到的数据进行转换或者整合。最终获得ModelAndView对象
            mv = ha.handle(processedRequest, response, mappedHandler.getHandler());

            if (asyncManager.isConcurrentHandlingStarted()) {
                return;
            }

            applyDefaultViewName(processedRequest, mv);
            // 调用拦截器的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);
        }
        // 后续处理:处理模型数据和渲染视图
        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);
            }
        }
    }
}
d>processDispatchResult()
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);
        }
    }

    // Did the handler return a view to render?
    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;
    }

    if (mappedHandler != null) {
        // Exception (if any) is already handled..
        // 调用拦截器的afterCompletion()
        mappedHandler.triggerAfterCompletion(request, response, null);
    }
}
SpringMVC的执行流程
  1. 用户向服务器发送请求,请求被SpringMVC 前端控制器 DispatcherServlet捕获。

  2. DispatcherServlet对请求URL进行解析,得到请求资源标识符(URI),判断请求URI对应的映射:

a) 不存在

i. 再判断是否配置了mvc:default-servlet-handler

ii. 如果没配置,则控制台报映射查找不到,客户端展示404错误

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-pEZfsxmP-1652669089209)(C:UserszhangxyDesktop笔记springSpringBoot、Spring、SpringMVC原理梳理.assetsimg006.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-KFW1MN4i-1652669089209)(C:UserszhangxyDesktop笔记springSpringBoot、Spring、SpringMVC原理梳理.assetsimg007.png)]

iii. 如果有配置,则访问目标资源(一般为静态资源,如:JS,CSS,HTML),找不到客户端也会展示404错误

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-uI2uQBUo-1652669089210)(C:UserszhangxyDesktop笔记springSpringBoot、Spring、SpringMVC原理梳理.assetsimg008.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-PCGDiMTx-1652669089210)(C:UserszhangxyDesktop笔记springSpringBoot、Spring、SpringMVC原理梳理.assetsimg009.png)]

b) 存在则执行下面的流程

  1. 根据该URI,调用HandlerMapping获得该Handler配置的所有相关的对象(包括Handler对象以及Handler对象对应的拦截器),最后以HandlerExecutionChain执行链对象的形式返回。

  2. DispatcherServlet 根据获得的Handler,选择一个合适的HandlerAdapter。

  3. 如果成功获得HandlerAdapter,此时将开始执行拦截器的preHandler(…)方法【正向】

  4. 提取Request中的模型数据,填充Handler入参,开始执行Handler(Controller)方法,处理请求。在填充Handler的入参过程中,根据你的配置,Spring将帮你做一些额外的工作:

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

b) 数据转换:对请求消息进行数据转换。如String转换成Integer、Double等

c) 数据格式化:对请求消息进行数据格式化。 如将字符串转换成格式化数字或格式化日期等

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

  1. Handler执行完成后,向DispatcherServlet 返回一个ModelAndView对象。

  2. 此时将开始执行拦截器的postHandle(…)方法【逆向】(Q1:为什么要逆向呢?)。

  3. 根据返回的ModelAndView(此时会判断是否存在异常:如果存在异常,则执行HandlerExceptionResolver进行异常处理)选择一个适合的ViewResolver进行视图解析,根据Model和View,来渲染视图。

  4. 渲染视图完毕执行拦截器的afterCompletion(…)方法【逆向】(Q2:为什么要逆向呢?)。

  5. 将渲染结果返回给客户端。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/890936.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号