在上一篇我們介紹了Servlet,這一篇主要來看一下MVC中用到的DispatcherServlet(繼承自HttpServlet)。
1. DispatcherServlet在web.xml中被聲明。
<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>/example/*</url-pattern> </servlet-mapping></web-app>
注:我們也可以在代碼中去進行設置,具體參考http://docs.spring.io/spring/docs/4.0.6.RELEASE/spring-framework-reference/htmlsingle/#mvc-container-config
2. DispatcherServlet包含的一些beans
3. 除了步驟2種默認提供的bean以外,Spring MVC還會在WEB-INF文件夾下尋找一個[servlet-name]-servlet.xml文件(步驟1中,會尋找example-servlet.xml這個文件), 創建這個文件中定義的beans。
如果需要修改默認的bean,可以在這個里面進行定義,加載時會覆蓋默認的bean。
4. 我們可以通過DispatcherServlet中的初始化方法,配置步驟3中的xml的路徑。
或者,如果你想用一個公用的xml,可以配置context-param并且不設置contextConfigLocation的值就可以了。
<web-app> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/root-context.xml</param-value> </context-param> <servlet> <servlet-name>dispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value></param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatcher</servlet-name> <url-pattern>/*</url-pattern> </servlet-mapping> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener></web-app>
5. 如果要讓mvc下的annotation起作用,需要在[servlet-name]-servlet.xml中增加一行。
<?xml version=1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <mvc:annotation-driven /></beans>
新聞熱點
疑難解答