第一步:新建一个动态web项目,目录结构如下:
第二步,定义web.xml文件
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>SpringMvcTest</display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <!-- 配置Spring IOC 容器 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:WebContent/config/applicationContext.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 配置SpringMVC 的 DispatcherServlet 控制器 --> <servlet> <servlet-name>dispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 配置DispatcherServlet的一个初始化参数:配置SpringMVC配置文件的位置名称 --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:WebContent/config/springmvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatcherServlet</servlet-name> <url-pattern>/*</url-pattern> </servlet-mapping> <!-- 配置编码方式过滤器,注意一点:要配置在所有过滤器的前面 --> <filter> <filter-name>characterEncodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>characterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- 为了使用SpringMVC框架实现REST风格,需要配置 HiddenHttpMethodFilter--> <filter> <filter-name>hiddenHttpMethodFilter</filter-name> <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class> </filter> <filter-mapping> <filter-name>hiddenHttpMethodFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app> 对于xmlns的理解如下:xmlns其实是xml namespace,xml的命名空间。之所以使用xmlns是为了防止多个xml文件同时使用时会引起冲突的问题。因此,给多个xml文件贴上标签,在xmlns里标明,就可以防止冲突的发生。首先,使用的语法是xmln:名字=“名字的路径”。如 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"。就是定义了一个路径为http://www.w3.org/2001/XMLSchema-instance,名字为xsi的语句。而bean、web-app这类在xmlns前面的,是一个标签,所有<bean></bean>、<web-app></web-app>,都会被标记在一起。xmlns表示默认的Namespace。例如Spring XML文档中的
1 xmlns="http://www.springframework.org/schema/beans"这一句表示该文档默认的XML Namespace为http://www.springframwork.org/schema/beans。对于默认的Namespace中的元素,可以不使用前缀。例如Spring XML文档中的
1 2 3 < bean id = "xxx" class = "xxx.xxx.xxx.Xxx" > < property name = "xxx" value = "xxxx" /> </ bean >xmlns:xsi表示使用xsi作为前缀的Namespace,当然前缀xsi需要在文档中声明。