现在主流的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包
SpringMVC是一个基于DispatcherServlet的MVC框架,每一个请求最先访问的都是DispatcherServlet,DispatcherServlet负责转发每一个Request请求给相应的Handler,Handler处理以后再返回相应的视图(View)和模型(Model),返回的视图和模型都可以不指定,即可以只返回Model或只返回View或都不返回。
DispatcherServlet是继承自HttpServlet的,既然SpringMVC是基于DispatcherServlet的,那么我们先来配置一下DispatcherServlet,好让它能够管理我们希望它管理的内容。HttpServlet是在web.xml文件中声明的。
<!-- Spring MVC配置 --> <!-- ====================================== --> <servlet> <servlet-name>spring</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 可以自定义servlet.xml配置文件的位置和名称,默认为WEB-INF目录下,名称为[<servlet-name>]-servlet.xml,如spring-servlet.xml <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/spring-servlet.xml</param-value> 默认 </init-param> --> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>spring</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <!-- Spring配置 --> <!-- ====================================== --> <listener> <listenerclass> org.springframework.web.context.ContextLoaderListener </listener-class> </listener> <!-- 指定Spring Bean的配置文件所在目录。默认配置在WEB-INF目录下 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:config/applicationContext.xml</param-value> </context-param>
spring-servlet.xml配置
spring-servlet这个名字是因为上面web.xml中<servlet-name>标签配的值为spring(<servlet-name>spring</servlet-name>),再加上“-servlet”后缀而形成的spring-servlet.xml文件名,如果改为springMVC,对应的文件名则为springMVC-servlet.xml。
<?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:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd 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>"> <!-- 启用spring mvc 注解 --> <context:annotation-config /> <!-- 设置使用注解的类所在的jar包 --> <context:component-scan base-package="controller"></context:component-scan> <!-- 完成请求和注解POJO的映射 --> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" /> <!-- 对转向页面的路径解析。prefix:前缀, suffix:后缀 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/jsp/" p:suffix=".jsp" /> </beans>
DispatcherServlet会利用一些特殊的bean来处理Request请求和生成相应的视图返回。
关于视图的返回,Controller只负责传回来一个值,然后到底返回的是什么视图,是由视图解析器控制的,在jsp中常用的视图解析器是InternalResourceViewResovler,它会要求一个前缀和一个后缀
在上述视图解析器中,如果Controller返回的是blog/index,那么通过视图解析器解析之后的视图就是/jsp/blog/index.jsp。
主要是说说Controller.
一个类使用了@Controller进行标记的都是Controller
package controller; import javax.servlet.http.HttpServletRequest; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import entity.User; @Controller //类似Struts的Action public class TestController { @RequestMapping("test/login.do") // 请求url地址映射,类似Struts的action-mapping public String testLogin(@RequestParam(value="username")String username, String password, HttpServletRequest request) { // @RequestParam是指请求url地址映射中必须含有的参数(除非属性required=false) // @RequestParam可简写为:@RequestParam("username") if (!"admin".equals(username) || !"admin".equals(password)) { return "loginError"; // 跳转页面路径(默认为转发),该路径不需要包含spring-servlet配置文件中配置的前缀和后缀 } return "loginSuccess"; } @RequestMapping("/test/login2.do") public ModelAndView testLogin2(String username, String password, int age){ // request和response不必非要出现在方法中,如果用不上的话可以去掉 // 参数的名称是与页面控件的name相匹配,参数类型会自动被转换 if (!"admin".equals(username) || !"admin".equals(password) || age < 5) { return new ModelAndView("loginError"); // 手动实例化ModelAndView完成跳转页面(转发),效果等同于上面的方法返回字符串 } return new ModelAndView(new RedirectView("../index.jsp")); // 采用重定向方式跳转页面 // 重定向还有一种简单写法 // return new ModelAndView("redirect:../index.jsp"); } @RequestMapping("/test/login3.do") public ModelAndView testLogin3(User user) { // 同样支持参数为表单对象,类似于Struts的ActionForm,User不需要任何配置,直接写即可 String username = user.getUsername(); String password = user.getPassword(); int age = user.getAge(); if (!"admin".equals(username) || !"admin".equals(password) || age < 5) { return new ModelAndView("loginError"); } return new ModelAndView("loginSuccess"); } @Resource(name = "loginService") // 获取applicationContext.xml中bean的id为loginService的,并注入 private LoginService loginService; //等价于spring传统注入方式写get和set方法,这样的好处是简洁工整,省去了不必要得代码 @RequestMapping("/test/login4.do") public String testLogin4(User user) { if (loginService.login(user) == false) { return "loginError"; } return "loginSuccess"; } }
以上4个方法示例,是一个Controller里含有不同的请求url,也可以采用一个url访问,通过url参数来区分访问不同的方法,代码如下:
package controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @Controller @RequestMapping("/test2/login.do") // 指定唯一一个*.do请求关联到该Controller public class TestController2 { @RequestMapping public String testLogin(String username, String password, int age) { // 如果不加任何参数,则在请求/test2/login.do时,便默认执行该方法 if (!"admin".equals(username) || !"admin".equals(password) || age < 5) { return "loginError"; } return "loginSuccess"; } @RequestMapping(params = "method=1", method=RequestMethod.POST) public String testLogin2(String username, String password) { // 依据params的参数method的值来区分不同的调用方法 // 可以指定页面请求方式的类型,默认为get请求 if (!"admin".equals(username) || !"admin".equals(password)) { return "loginError"; } return "loginSuccess"; } @RequestMapping(params = "method=2") public String testLogin3(String username, String password, int age) { if (!"admin".equals(username) || !"admin".equals(password) || age < 5) { return "loginError"; } return "loginSuccess"; } }
其实RequestMapping在Class上,可看做是父Request请求url,而RequestMapping在方法上的可看做是子Request请求url,父子请求url最终会拼起来与页面请求url进行匹配,因此RequestMapping也可以这么写:
package controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller @RequestMapping("/test3/*") // 父request请求url public class TestController3 { @RequestMapping("login.do") // 子request请求url,拼接后等价于/test3/login.do public String testLogin(String username, String password, int age) { if (!"admin".equals(username) || !"admin".equals(password) || age < 5) { return "loginError"; } return "loginSuccess"; } }
在SpringMVC中常用的注解还有@PathVariable,@RequestParam,@PathVariable标记在方法的参数上,利用它标记的参数可以利用请求路径传值,看下面一个例子
@RequestMapping(value="/comment/{blogId}", method=RequestMethod.POST) public void comment(Comment comment,@PathVariable int blogId, HttpSession session, HttpServletResponse response) throws IOException { }
在该例子中,blogId是被@PathVariable标记为请求路径变量的,如果请求的是/blog/comment/1.do的时候就表示blogId的值为1. 同样@RequestParam也是用来给参数传值的,但是它是从头request的参数里面取值,相当于request.getParameter("参数名")方法。
在Controller的方法中,如果需要WEB元素HttpServletRequest,HttpServletResponse和HttpSession,只需要在给方法一个对应的参数,那么在访问的时候SpringMVC就会自动给其传值,但是需要注意的是在传入Session的时候如果是第一次访问系统的时候就调用session会报错,因为这个时候session还没有生成。
====================================================================
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-
class
>org.springframework.web.servlet.DispatcherServlet</servlet-
class
>
<init-param>
<description>加载/WEB-INF/spring-mvc/目录下的所有XML作为Spring MVC的配置文件</description>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-mvc/*.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
<?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:mvc=
"http://www.springframework.org/schema/mvc"
xmlns:p=
"http://www.springframework.org/schema/p"
xmlns:context=
"http://www.springframework.org/schema/context"
xmlns:aop=
"http://www.springframework.org/schema/aop"
xmlns:tx=
"http://www.springframework.org/schema/tx"
xsi:schemaLocation="http:
//www.springframework.org/schema/beans
http:
//www.springframework.org/schema/beans/spring-beans-3.0.xsd
http:
//www.springframework.org/schema/context
http:
//www.springframework.org/schema/context/spring-context-3.0.xsd
http:
//www.springframework.org/schema/aop
http:
//www.springframework.org/schema/aop/spring-aop-3.0.xsd
http:
//www.springframework.org/schema/tx
http:
//www.springframework.org/schema/tx/spring-tx-3.0.xsd
http:
//www.springframework.org/schema/mvc
http:
//www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http:
//www.springframework.org/schema/context
http:
//www.springframework.org/schema/context/spring-context-3.0.xsd">
<!--
使Spring支持自动检测组件,如注解的Controller
-->
<context:component-scan base-package=
"com.minx.crm.web.controller"
/>
<bean id=
"viewResolver"
class
=
"org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix=
"/WEB-INF/jsp/"
p:suffix=
".jsp"
/>
</beans>
|
1
2
3
4
5
6
7
8
9
10
11
|
package com.minx.crm.web.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public
class
IndexController {
@RequestMapping(
"/index"
)
public
String index() {
return
"index"
;
}
}
|
1
2
3
4
5
6
7
8
9
|
@Controller
public
class
IndexController {
@RequestMapping(
"/index/{username}"
)
public
String index(@PathVariable(
"username"
) String username) {
System.out.
print
(username);
return
"index"
;
}
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
|
@Controller
public
class
LoginController {
@RequestMapping(value =
"/login"
, method = RequestMethod.GET)
public
String login() {
return
"login"
;
}
@RequestMapping(value =
"/login"
, method = RequestMethod.POST)
public
String login2(HttpServletRequest request) {
String username = request.getParameter(
"username"
).trim();
System.out.println(username);
return
"login2"
;
}
}
|
1
|
return
"redirect:/login2"
|
1
2
3
4
5
6
|
@RequestMapping(value =
"login"
, method = RequestMethod.POST)
public
String testParam(HttpServletRequest request, HttpServletResponse response, HttpSession session) {
String username = request.getParameter(
"username"
);
System.out.println(username);
return
null;
}
|
1
2
3
4
5
6
|
@RequestMapping(value =
"login"
, method = RequestMethod.POST)
public
String testParam(HttpServletRequest request, HttpServletResponse response, HttpSession session,@RequestParam(
"username"
) String username) {
String username = request.getParameter(
"username"
);
System.out.println(username);
return
null;
}
|
1
2
3
4
5
|
@RequestMapping(value =
"login"
, method = RequestMethod.POST)
public
String testParam(PrintWriter out, @RequestParam(
"username"
) String username) {
out.println(username);
return
null;
}
|
1
2
3
4
5
6
7
|
public
class
User{
private
long id;
private
String username;
private
String password;
…此处省略getter,setter...
}
|
1
2
3
4
5
|
@RequestMapping(value =
"login"
, method = RequestMethod.POST)
public
String testParam(PrintWriter out, User user) {
out.println(user.getUsername());
return
null;
}
|
1
2
3
4
5
|
@RequestMapping(value =
"login"
, method = RequestMethod.POST)
public
String testParam(User user, Map model) {
model.put(
"user"
,user);
return
"view"
;
}
|
1
2
3
4
5
6
7
8
9
10
11
12
|
public
class
MyInteceptor
implements
HandlerInterceptor {
public
boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o)
throws Exception {
return
false;
}
public
void postHandle(HttpServletRequest request, HttpServletResponse response, Object o, ModelAndView mav)
throws Exception {
}
public
void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object o, Exception excptn)
throws Exception {
}
}
|
1
2
3
4
5
6
|
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path=
"/index.htm"
/>
<bean
class
=
"com.minx.crm.web.interceptor.MyInterceptor"
/>
</mvc:interceptor>
</mvc:interceptors>
|
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource" p:basename="message"> </bean>
1
2
3
4
|
<bean id=
"messageSource"
class
=
"org.springframework.context.support.ResourceBundleMessageSource"
p:
basename
=
"message"
>
</bean>
|