SpringMVC 之六(运行流程、与 Spring 整合及与 Struts2 对比)

18、SpringMVC 运行流程

在这里插入图片描述
存在对应的映射的情况:

  • 由 HandlerMapping 获取 HandlerExecutionChain 对象,即由 RequestMappingHandlerMapping 获取 HandlerExcutionChain 对象
    在这里插入图片描述
    在这里插入图片描述
  • 获取 HandlerAdapter(RequestMappingHandlerAdapter)对象
    在这里插入图片描述
  • 调用拦截器的 PreHandler 方法
    在这里插入图片描述
  • 调用目标 Handler 的目标方法得到 ModelAndView 对象
    在这里插入图片描述
    在这里插入图片描述
  • 调用拦截器的 postHandler 方法
    在这里插入图片描述
  • 处理视图
    在这里插入图片描述
    若存在异常,由 HandlerExceptionResolver 组件处理异常,得到新的 ModelAndView 对象
    在这里插入图片描述
    若不存在异常,由 ViewResolver 组件根据 ModelAndView 对象得到实际的 View
    在这里插入图片描述
  • 渲染视图
    在这里插入图片描述
    其中,调用 InternalResourceView.renderMergedOutputModel() 方法进行请求转发
    在这里插入图片描述
  • 调用拦截器的 afterCompletion 方法
    在这里插入图片描述

19、在 Spring 的环境下使用 SpringMVC

(1)需要进行 Spring 整合 SpringMVC 吗?还是否需要再加入 Spring 的 IOC 容器?是否需要在 web.xml 文件中配置启动 Spring IOC 容器的 ContextLoaderListener ?

  • 需要:通常情况下,类似于数据源,事务,整合其他框架都是放在 Spring 的配置文件中(而不是放在 SpringMVC 的配置文件中)。实际上放入 Spring 配置文件对应的 IOC 容器中的还有 Service 和 Dao 。

  • 不需要:都放在 SpringMVC 的配置文件中。也可以分多个 Spring 的配置文件,然后使用 import 节点导入其他的配置文件

(2)问题:若 Spring 的 IOC 容器和 SpringMVC 的 IOC 容器扫描的包有重合的部分,就会导致有的 bean 会被创建两次。

(3)解决:

  • 使 Spring 的 IOC 容器扫描的包和 SpringMVC 的 IOC 容器扫描的包没有重合的部分。
  • 使用 exclude-filter 和 include-filter 子节点来规定只能扫描的注解

beans.xml

	<context:component-scan base-package="com.mycode.springmvc">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
        <context:exclude-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice"/>
    </context:component-scan>

springmvc.xml

	<context:component-scan base-package="com.mycode.springmvc" use-default-filters="false ">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
        <context:include-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice"/>
    </context:component-scan>

(4)在 Spring MVC 配置文件中引用业务层的 Bean

  • 多个 Spring IOC 容器之间可以设置为父子关系, 以实现良好的解耦。

  • Spring MVC WEB 层容器可作为 “业务层” Spring 容器的子容器:即 WEB 层容器可以引用业务层容器的 Bean,而业务层容器却访问不到 WEB 层容器的 Bean(Handler 可以引用 Service,而 Service 却不能引用 Handler)
    在这里插入图片描述

20、SpringMVC 对比 Struts2

(1)Spring MVC 的入口是 Servlet, 而 Struts2 是 Filter

(2)Spring MVC 会稍微比 Struts2 快些, Spring MVC 是基于方法设计, 而 Sturts2 是基于类, 每次发一次请求都会实例一个 Action。

(3)Spring MVC 使用更加简洁,开发效率Spring MVC确实比 struts2 高:支持 JSR303,处理 ajax 的请求更方便

(4)Struts2 的 OGNL 表达式使页面的开发效率相比 Spring MVC 更高些。

猜你喜欢

转载自blog.csdn.net/Lu1048728731/article/details/112468451