1. 程式人生 > >Spring MVC重要元件及其流程

Spring MVC重要元件及其流程

8. 將渲染結果返回給客戶端。
二、具體程式碼配置

1、DispatcherServletweb.xml中的配置

<servlet>  
    <servlet-name>chapter2</servlet-name>  
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
    <load-on-startup>1</load-on-startup>  
</servlet>  
<servlet-mapping>  
    <servlet-name>chapter2</servlet-name>  
    <url-pattern>/</url-pattern>  
</servlet-mapping>  

load-on-startup表示啟動容器時初始化該Servlet;

url-pattern表示哪些請求交給Spring Web MVC處理, “/” 是用來定義預設servlet對映的。也可以如“*.html”表示攔截所有以html為副檔名的請求。

該DispatcherServlet預設使用WebApplicationContext作為上下文,Spring預設配置檔案為“/WEB-INF/[servlet名字]-servlet.xml”。

該DispatcherServlet預設使用WebApplicationContext作為上下文,當然也可以自己配置上下文。如下:

<servlet>
   <servlet-name>DispatcherServlet</servlet-name>
   <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<span style="color:#FF0000;">   <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>/WEB-INF/config/spring/springmvc-servlet.xml</param-value>
   </init-param></span>
   <load-on-startup>1</load-on-startup>
</servlet>

2、上下文關係

<context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>/WEB-INF/config/spring/applicationContext-resources.xml</param-value>
</context-param>
<listener>
  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

contextConfigLocation:表示用於載入Bean的配置檔案;

contextClass:表示用於載入Bean的ApplicationContext實現類,預設WebApplicationContext。

ContextLoaderListener初始化上下文和DispatcherServlet初始化上下文的關係: