springMVC流程的学习和理解

先用一个图来表示
基本流程图这个网上很容易找到

基本流程图

《springMVC流程的学习和理解》

1. 用户发送请求到前端控制器(DispatcherServlet)

前端控制器是springMVC的重要部分,位于中心,提供整个框架访问点,起到交换的作用,而且与Spring IoC容器集成。(IoC容器中包含了Bean,详细IoC讲解开涛的博客)

在实际开发中,只需要在web.xml中进行配置,其他组件由框架提供,配置如下:

    <servlet>
        <servlet-name>springMVC</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
          <!--配置spring.xml作为mvc的配置文件-->
          <param-name>contextConfigLocation</param-name>
          <param-value>classpath:spring/springmvc.xml </param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>springMVC</servlet-name>
        <url-pattern>*.action</url-pattern>
    </servlet-mapping>
通过过滤(根据URL)的方式进入前端控制器(init-param标签中的contextConfigLocation会在后面说到)

2和3. 处理器映射器HandlerMapping

根据请求的url查找Handler
HandlerMapping负责根据用户请求找到Handler即处理器,springmvc提供了不同的映射器实现不同的映射方式,例如:配置文件方式,实现接口方式,注解方式等。在spring.xml中使用自动扫描的方式:

<context:component-scan base-package="top.youzipi.test.controller"></context:component-scan>

然后返回前端控制器

4. 处理器适配器HandlerAdapter

需要controller继承Controller或者@Controller,前端控制器会根据controller对应的controller类型来调用相应的HandlerAdapter来进行处理,不需要什么操作

5和6和7. 处理器Handler

就是编写Controller类


    ```
    @Controller
    public class TestController {
        @Autowired
        private TestService testService;
        //信息查询
        @RequestMapping("/test")
        public ModelAndView test() throws Exception{
            List<Test> testList=testService.findTestList(null);
            ModelAndView modelAndView=new ModelAndView();
            //相当于request中setAttribute
            modelAndView.addObject("testList",testList);
            modelAndView.setViewName("test");
    
            return modelAndView;
        }
    
    }
    ```

返回ModelAndView对象

8和9. 视图解析器View resolver

进行视图解析,根据逻辑视图名解析成真正的视图(view)。View Resolver负责将处理结果生成View视图:View Resolver首先根据逻辑视图名解析成物理视图名即具体的页面地址,再生成View视图对象,最后对View进行渲染将处理结果通过页面展示给用户。

在spring.xml中配置

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/webapp/view/"/>
        <property name="suffix" value=".jsp" />
    </bean>

10和11. 视图View

编写JSP、excel、pdf等向用户显示的内容

其他

contextConfigLocation实现ContextLoaderListener监听器,在web.xml中定义

  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:spring/applicationContext-*.xml</param-value>
  </context-param>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

ContextLoaderListener监听器的作用就是启动Web容器时,自动装配ApplicationContext的配置信息。在web.xml配置这个监听器,启动容器时,就会默认执行它实现的方法。

在这里使用这个监听器的作用是方便加载Dao、Service、DataSource、Bean等,如applicationContext-dao.xml,applicationContext-service.xml。如果使用mybatis这些配置文件中可以加入mapper.xml文件,提供数据库操作

谢谢浏览~~~
如果有不正确的地方欢迎指出~~~
≥ω≤ ≥ω≤ ≥ω≤

    原文作者:Pursuer
    原文地址: https://segmentfault.com/a/1190000016088760
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞