使用的IDE工具是MyEclipse2014, spring版本為3.1.1
在使用Spring MVC時需要修改web.xml配置文件,web.xml默認放在WEB-INF目錄下。
1.web.xml約束文檔
用MyEclipse生成的約束文檔有時不對,可以使用下面的模版
1 <?xml version="1.0" encoding="UTF-8"?> 2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 3 xmlns="http://java.sun.com/xml/ns/javaee" 4 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" 5 id="WebApp_ID" version="3.0"> 6 7 </web-app>
2.配置DispatcherServlet
Spring MVC工作時其核心的部分是DispatcherServlet,這個servlet就是個門戶,所有的請求和相應都需要經過它,我們需要在web.xml來指明它。
<servlet> <servlet-name>spring</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-servlet.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>spring</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping>
配置它就像配置一個我們自己寫的Servlet一樣,這里不做說明。主要是這個Servlet在加載時需要讀取關於Sring的配置信息文檔(如:Spring-serlvet.xml)。這個文檔的位置放在不對就會導致該Servlet加載失敗。
2.1 使用默認配置路徑
使用默認配置路徑時,Spring-servlet.xml應該放在WEB-INF/下,這個而且這個文件的文件名不能隨便命名。命名方式為
<servlet-name>name</servlet-name>中的name連接 -servlet.xml, 如 <servlet-name>SpringTest</servlet-name>時那么配置文件名為SpringTest-servlet.xml
2.2 指定路徑名
上面的配置文件中就是使用的是指定路徑名方式。
<init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-servlet.xml</param-value> </init-param>
其中的classpath為/WEB-INF/classes目錄,所以我們應該把配置文件放在這個目錄下。也可以直接放在工程的src目錄下,Myeclipse會自動將其放在classes目錄中。當然我們也可以指定放在別的目錄下,比如我們在WEB-INF下新建config目錄,將配置文件放在其中,那我們也應該設置相應的參數。
<init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/config/spring-servlet.xml</param-value> </init-param>
2.3 特殊情況
如果我們的web.xml只是用了一個servlet的話可以用上面的方式來指定spring-servlet.xml,如果定義了多個servlet的話,該文件只能通過<context-param></context-param>來配置,因為多個servlet可以共享context中的內容。配置方式如下
1 <context-param> 2 <param-name>contextConfigLocation</param-name> 3 <param-value>/WEB-INF/transport-servlet.xml</param-value> 4 </context-param>
3. Spring MVC框架的配置
3.1約束文檔的引入
我們繼續沿用sping-servlet.xml配置文檔,下面的也一樣。MyEclipse生成的配置文檔引入的約束並不全,我們可以使用下面的約束。
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd"> </beans>
4.SpringMVC + Maven
1.MyEclipse中配置maven
這里不使用MyEclipse自帶的maven,通過官網下載進行配置。配置教程 鏈接地址1 該教程只需看前面配置maven這一部分。
