ShenZhun的Blog

你要保守你心,胜过保守一切,因为一生的果效是由心发出。

导航

Spring MVC的基本配置

1. 导入jar包:

  如果WEB项目用到Spring框架,则可以将Spring所发行的jar包都放到WEB-INF/lib下面。

2. 在web.xml文件中加入Spring MVC的配置,Spring MVC的工作是基于servlet,所有的请求都交给DispatcherServlet处理。servlet-name可以为项目名称,映射的url-pattern为"/"表示拦截所有的请求。

 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     <!-- Spring MVC 配置开始 -->
 7     <servlet>
 8         <servlet-name>demo</servlet-name>
 9         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
10         <load-on-startup>1</load-on-startup>
11     </servlet>
12     <servlet-mapping>
13         <servlet-name>demo</servlet-name>
14         <url-pattern>/</url-pattern>
15     </servlet-mapping>
16     <!-- Spring MVC 配置结束 -->
17 </web-app>

3. 在web.xml的同级目录下创建Spring MVC的配置文件,取名为"项目名-servlet.xml"。如:"demo-servlet.xml",内容如下:

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3     xmlns:mvc="http://www.springframework.org/schema/mvc"
 4     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 5     xmlns:p="http://www.springframework.org/schema/p"
 6     xmlns:context="http://www.springframework.org/schema/context"
 7     xsi:schemaLocation="
 8         http://www.springframework.org/schema/beans
 9         http://www.springframework.org/schema/beans/spring-beans.xsd
10         http://www.springframework.org/schema/mvc
11         http://www.springframework.org/schema/mvc/spring-mvc.xsd
12         http://www.springframework.org/schema/context
13         http://www.springframework.org/schema/context/spring-context.xsd">
14     <!-- 设置基于annotation的配置 -->
15     <mvc:annotation-driven enable-matrix-variables="true"/>
16     <!-- 设置Controller的包自动扫描 -->
17     <context:component-scan base-package="tk.zhun.demo.controller"/>
18     <!-- 设置默认的视图 -->
19     <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
20         <property name="prefix" value="/WEB-INF/jsp/"></property>
21         <property name="suffix" value=".jsp"></property>
22     </bean>
23 </beans>

如果在用jsp做视图时,用到了JSTL,最好在bean的配置里添加属性如下:

1 <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>

(未完待续)

posted on 2014-11-18 09:24  shenzhun  阅读(111)  评论(0)    收藏  举报