1.引入相应的jar包,不用说
2.配置相应的xml文件

1 <?xml version="1.0" encoding="UTF-8"?>
2 <beans
3 xmlns="http://www.springframework.org/schema/beans"
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="http://www.springframework.org/schema/beans
8 http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
9 http://www.springframework.org/schema/context
10 http://www.springframework.org/schema/context/spring-context-2.5.xsd">
11
12 <!-- 对web包中的所有类进行扫描,以完成Bean创建和自动依赖注入的功能 -->
13 <context:component-scan base-package="com.sxt"/>
14
15 <!-- 启动Spring MVC的注解功能,完成请求和注解POJO的映射 -->
16 <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/>
17
18 <!--对模型视图名称的解析,即在模型视图名称添加前后缀 -->
19 <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
20 p:suffix=".jsp"/>
21 </beans>
View Code
3.controller并不需要实现什么类,而且和struts2一样每个类里可以有很多个方法
1)类前加注解@Controller(或者@Component也行),意思是由容器帮你生成这个类;还需要加一个@RequestMapping("/user.do"),表示当调用user.do的时候,就会调用这个类。spring mvc 同时还有一个很强大的@SessionAttributes("username","userId");意思是把username和userId放到session里保存,当然@SessionAttributes注解也要加在类上。注意:@RequestMapping()这个注解可以加在类上,也可以加在方法上。如果加在类上,那么多个方法怎么区分执行那个方法呢,@RequestMapping(params="method=reg"),传一个参数,然后通过参数不同来区分执行那个方法发生哪个跳转,当然method这个参数名字可以随便起。
2)如果有一个方法,那么user.do就可以调用其中的方法,但是如果有多个方法怎么办呢?在你跳到这个方法之前,传一个参数比如method,spring里有一个@RequestMapping(params="method=reg")加到方法前,其中当参数method(当然可以叫其他名字),是reg的时候,就调用这个方法
3)spring的传参,非常简单,只要把需要的表单数据,加到这个方法上,当参数传过来即可:
例如:public String saveUser(String userName,HttpServletRequest request){.....}
这样就把userName和request的值取到了,直接用就可以了
其中如果表单的参数与方法里的参数不对应的话,用@RequestParam
public String reg3(@RequestParam("uname") String name,HttpServletRequest req,ModelMap map)
其中spring mvc还有一个ModelMap,map类型的可以传参,直接map.put("....","...");表单就可以取到值
4)返回值:方法返回的String,然后配置文件里配置了返回值的前缀和后缀,通过返回值就可以直接找到对应的页面。例如:return "login",假如配置文件配置的前缀是/pages,后缀是.jsp,那么随着return就会调到/pages/login.jsp
写的可能有些简单,且看下边的例子
现在主流的Web MVC框架除了Struts这个主力 外,其次就是Spring MVC了,因此这也是作为一名程序员需要掌握的主流框架,框架选择多了,应对多变的需求和业务时,可实行的方案自然就多了。不过要想灵活运用Spring MVC来应对大多数的Web开发,就必须要掌握它的配置及原理。
一、Spring MVC环境搭建:(Spring 2.5.6 + Hibernate 3.2.0)
1. jar包引入
Spring 2.5.6:spring.jar、spring-webmvc.jar、commons-logging.jar、cglib-nodep-2.1_3.jar
Hibernate 3.6.8:hibernate3.jar、hibernate-jpa-2.0-api-1.0.1.Final.jar、antlr-2.7.6.jar、commons-collections-3.1、dom4j-1.6.1.jar、javassist-3.12.0.GA.jar、jta-1.1.jar、slf4j-api-1.6.1.jar、slf4j-nop-1.6.4.jar、相应数据库的驱动jar包
2. web.xml配置(部分)
04 |
<servlet-name>spring</servlet-name> |
05 |
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> |
12 |
<load-on-startup>1</load-on-startup> |
16 |
<servlet-name>spring</servlet-name> |
17 |
<url-pattern>*.do</url-pattern> |
25 |
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> |
31 |
<param-name>contextConfigLocation</param-name> |
32 |
<param-value>classpath:config/applicationContext.xml</param-value> |
3. spring-servlet.xml配置
spring-servlet这个名字是因为上面web.xml中<servlet-name>标签配的值为spring(<servlet-name>spring</servlet-name>),再加上“-servlet”后缀而形成的spring-servlet.xml文件名,如果改为springMVC,对应的文件名则为springMVC-servlet.xml。
01 |
<?xml version="1.0" encoding="UTF-8"?> |
02 |
<beans xmlns="http://www.springframework.org/schema/beans" |
03 |
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:p="http://www.springframework.org/schema/p" |
04 |
xmlns:context="http://www.springframework.org/schema/context" |
05 |
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd |
06 |
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd |
07 |
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd |
08 |
http://www.springframework.org/schema/context <a href="http://www.springframework.org/schema/context/spring-context-3.0.xsd">http://www.springframework.org/schema/context/spring-context-3.0.xsd</a>"> |
11 |
<context:annotation-config /> |
14 |
<context:component-scan base-package="controller"></context:component-scan> |
17 |
<beanclass="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/> |
20 |
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"p:prefix="/jsp/" p:suffix=".jsp" /> |
4. applicationContext.xml配置
01 |
<?xml version="1.0" encoding="UTF-8"?> |
02 |
<beans xmlns="http://www.springframework.org/schema/beans" |
03 |
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" |
04 |
xmlns:aop="http://www.springframework.org/schema/aop" |
05 |
xmlns:tx="http://www.springframework.org/schema/tx" |
07 |
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd |
08 |
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd |
09 |
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"> |
12 |
<bean id="sessionFactory"class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> |
13 |
<property name="configLocation"> |
14 |
<value>classpath:config/hibernate.cfg.xml</value> |
19 |
<bean id="transactionManager"class="org.springframework.orm.hibernate3.HibernateTransactionManager"> |
20 |
<property name="sessionFactory"> |
21 |
<ref local="sessionFactory"/> |
26 |
<tx:annotation-driven transaction-manager="transactionManager"proxy-target-class="true"/> |
29 |
<bean id="loginService" class="service.LoginService"></bean> |
32 |
<bean id="hibernateDao" class="dao.HibernateDao"> |
33 |
<property name="sessionFactory" ref="sessionFactory"></property> |
二、详解
Spring MVC与Struts从原理上很相似(都是基于MVC架构),都有一个控制页面请求的Servlet,处理完后跳转页面。看如下代码(注解):
03 |
import javax.servlet.http.HttpServletRequest; |
05 |
import org.springframework.stereotype.Controller; |
06 |
import org.springframework.web.bind.annotation.RequestMapping; |
07 |
import org.springframework.web.bind.annotation.RequestParam; |
12 |
public class TestController { |
14 |
@RequestMapping("test/login.do") |
15 |
publicString testLogin(@RequestParam(value="username")String username, String password, HttpServletRequest request) { |
19 |
if (!"admin".equals(username) || !"admin".equals(password)) { |
22 |
return "loginSuccess"; |
25 |
@RequestMapping("/test/login2.do") |
26 |
public ModelAndView testLogin2(String username, String password, int age){ |
30 |
if (!"admin".equals(username) || !"admin".equals(password) || age < 5) { |
31 |
return newModelAndView("loginError"); |
33 |
return new ModelAndView(newRedirectView("../index.jsp")); |
38 |
@RequestMapping("/test/login3.do") |
39 |
public ModelAndView testLogin3(User user) { |
41 |
String username = user.getUsername(); |
42 |
String password = user.getPassword(); |
43 |
int age = user.getAge(); |
45 |
if (!"admin".equals(username) || !"admin".equals(password) || age < 5) { |
46 |
return new ModelAndView("loginError"); |
48 |
return new ModelAndView("loginSuccess"); |
51 |
@Resource(name = "loginService") |
52 |
privateLoginService loginService; |
54 |
@RequestMapping("/test/login4.do") |
55 |
public String testLogin4(User user) { |
56 |
if (loginService.login(user) == false) { |
59 |
return "loginSuccess"; |
以上4个方法示例,是一个Controller里含有不同的请求url,也可以采用一个url访问,通过url参数来区分访问不同的方法,代码如下:
03 |
import org.springframework.stereotype.Controller; |
04 |
import org.springframework.web.bind.annotation.RequestMapping; |
05 |
import org.springframework.web.bind.annotation.RequestMethod; |
08 |
@RequestMapping("/test2/login.do") |
09 |
public class TestController2 { |
12 |
public String testLogin(String username, String password, int age) { |
15 |
if (!"admin".equals(username) || !"admin".equals(password) || age < 5) { |
18 |
return "loginSuccess"; |
21 |
@RequestMapping(params = "method=1", method=RequestMethod.POST) |
22 |
public String testLogin2(String username, String password) { |
26 |
if (!"admin".equals(username) || !"admin".equals(password)) { |
29 |
return "loginSuccess"; |
32 |
@RequestMapping(params = "method=2") |
33 |
public String testLogin3(String username, String password, int age) { |
34 |
if (!"admin".equals(username) || !"admin".equals(password) || age < 5) { |
37 |
return "loginSuccess"; |
其实RequestMapping在Class上,可看做是父Request请求url,而RequestMapping在方法上的可看做是子Request请求url,父子请求url最终会拼起来与页面请求url进行匹配,因此RequestMapping也可以这么写:
03 |
import org.springframework.stereotype.Controller; |
04 |
import org.springframework.web.bind.annotation.RequestMapping; |
07 |
@RequestMapping("/test3/*") |
08 |
public class TestController3 { |
10 |
@RequestMapping("login.do") |
11 |
public String testLogin(String username, String password, int age) { |
12 |
if (!"admin".equals(username) || !"admin".equals(password) || age < 5) { |
15 |
return "loginSuccess"; |
三、结束语
掌握以上这些Spring MVC就已经有了很好的基础了,几乎可应对与任何开发,在熟练掌握这些后,便可更深层次的灵活运用的技术,如多种视图技术,例如 Jsp、Velocity、Tiles、iText 和 POI。Spring MVC框架并不知道使用的视图,所以不会强迫您只使用 JSP 技术。