DispatcherServlet的用法

DispatcherServlet其實是一個Servlet(它從HttpServlet繼承而來)。和其它Servlet同樣,DispatcherServlet定義在web應用的web.xml文件裏。DispatcherServlet處理的請求必須在同一個web.xml文件裏使用url-mapping定義映射。下面的例子演示瞭如何配置DispatcherServlet。 <web-app>     <servlet>         <servlet-name>example</servlet-name>         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>         <load-on-startup>1</load-on-startup>     </servlet>     <servlet-mapping>         <servlet-name>example</servlet-name>         <url-pattern>*.form</url-pattern>     </servlet-mapping> </web-app> 在上面的例子裏,全部以.form結尾的請求都會由名爲example的DispatcherServlet處理。這只是配置Spring Web MVC的第一步。接下來須要配置DispatcherServlet自己和Spring Web MVC 框架用到的其餘的bean。 正如在第 3.8 節 「ApplicationContext」中所描述的,Spring中的ApplicationContext能夠被限制在不一樣的做用域(scope)中。在web MVC框架中,每一個DispatcherServlet有它本身的WebApplicationContext,這個context繼承了根 WebApplicationContext的全部bean定義。這些繼承的bean也能夠在每一個serlvet本身的所屬的域中被覆蓋(override),覆蓋後的bean能夠被設置成只有這個servlet實例本身才可使用的屬性。 Spring Web MVC中的Context體系 在DispatcherServlet的初始化過程當中,Spring會在web應用的WEB-INF文件夾下尋找名爲[servlet-name]-servlet.xml的配置文件,生成文件中定義的bean。這些bean會覆蓋在全局範圍(global cope)中定義的同名的bean。 下面這個例子展現了在web.xml中DispatcherServlet的配置: <web-app>     ...     <servlet>         <servlet-name>golfing</servlet-name>         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>         <load-on-startup>1</load-on-startup>     </servlet>     <servlet-mapping>         <servlet-name>golfing</servlet-name>         <url-pattern>*.do</url-pattern>     </servlet-mapping> </web-app> 要進行如上的servlet配置,你還須要配置/WEB-INF/golfing-servlet.xml這樣一個文件。golfing-servlet.xml這個文件應該聲明你在Spring Web MVC 框架中須要的bean。 這個文件的路徑也能夠經過web.xml中servlet的初始化參數來更改。(詳情見下面的例子。) WebApplicationContext僅僅是一個擁有web應用必要功能的普通ApplicationContext。它與一個標準的ApplicationContext的不一樣之處在於,它可以解析theme(參考第 13.7 節 「使用主題」),而且它知道本身與哪一個servlet相關聯(經過ServletContext)。WebApplicationContext被綁定在ServletContext上,當你須要的時候,可使用RequestContextUtils提供的靜態方法找到WebApplicationContext。 Spring的DispatcherServlet有一組特殊的bean,用來處理請求和渲染相應的視圖。這些bean包含在Spring的框架裏,能夠在WebApplicationContext中配置,配置方式與配置其它bean相同。這些bean中的每個都在下文做詳細描述。此刻讀者只需知道它們的存在,便繼續對DispatcherServlet進行討論。對大多數bean,Spring都提供了合理的缺省值,因此在開始階段,你沒必要擔憂如何對其進行配置。
相關文章
相關標籤/搜索