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文件,提供數據庫操作


謝謝瀏覽~~~
如果有不正確的地方歡迎指出~~~
≥ω≤ ≥ω≤ ≥ω≤

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章