SpringMVC与SiteMesh2.4无缝整合并借助JSR303规范实现表单验证
这是个WebProject,SpringMVC用的是3.1.1,SiteMesh用的是2.4
1. <?xml version="1.0" encoding="UTF-8"?>
2. <web-app version="2.5"
3. xmlns="http://java.sun.com/xml/ns/javaee"
4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
5. xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
6. http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
7. <servlet>
8. <servlet-name>user</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>user</servlet-name>
14. <url-pattern>/</url-pattern>
15. </servlet-mapping>
16.
17. <filter>
18. <filter-name>sitemesh</filter-name>
19. <filter-class>com.opensymphony.sitemesh.webapp.SiteMeshFilter</filter-class>
20. </filter>
21. <filter-mapping>
22. <filter-name>sitemesh</filter-name>
23. <url-pattern>/*</url-pattern>
24. </filter-mapping>
25.
26. <filter>
27. <filter-name>SpringCharacterEncodingFilter</filter-name>
28. <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
29. <init-param>
30. <param-name>encoding</param-name>
31. <param-value>UTF-8</param-value>
32. </init-param>
33. </filter>
34. <filter-mapping>
35. <filter-name>SpringCharacterEncodingFilter</filter-name>
36. <url-pattern>/*</url-pattern>
37. </filter-mapping>
38. </web-app>
1. <?xml version="1.0" encoding="UTF-8"?>
2. <beans xmlns="http://www.springframework.org/schema/beans"
3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4. xmlns:mvc="http://www.springframework.org/schema/mvc"
5. xmlns:context="http://www.springframework.org/schema/context"
6. xsi:schemaLocation="http://www.springframework.org/schema/beans
7. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
8. http://www.springframework.org/schema/mvc
9. http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
10. http://www.springframework.org/schema/context
11. http://www.springframework.org/schema/context/spring-context-3.0.xsd">
12. <context:component-scan base-package="com.jadyer"/>
13.
14. <!-- 如果ClassPath中有JSR-303的实现,例如Hibernate-Validator,则支持@Valid修饰的参数 -->
15. <!-- JSR-303 support will be detected on classpath and enabled automatically -->
16. <mvc:annotation-driven/>
17.
18. <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
19. <property name="prefix" value="/WEB-INF/jsp/"/>
20. <property name="suffix" value=".jsp"/>
21. </bean>
22. </beans>
1. <?xml version="1.0" encoding="UTF-8"?>
2. <decorators defaultdir="/WEB-INF/sitemesh/">
3. <decorator name="main" page="basic.jsp">
4. <pattern>/*</pattern>
5. </decorator>
6. </decorators>
1. <%@ page language="java" pageEncoding="UTF-8"%>
2. <%@ taglib prefix="decorator" uri="http://www.opensymphony.com/sitemesh/decorator"%>
3. <h1>User Manager</h1>
4. <hr/>
5. <decorator:body/>
1. <%@ page language="java" pageEncoding="UTF-8"%>
2. <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
3. <form:form method="POST" modelAttribute="user">
4. username:<form:input path="username"/><form:errors path="username"/><br/>
5. nickname:<form:input path="nickname"/><form:errors path="nickname"/><br/>
6. password:<form:password path="password"/><form:errors path="password"/><br/>
7. email:<form:input path="email"/><form:errors path="email"/><br/>
8. <input type="submit"/>
9. </form:form>
1. <%@ page language="java" pageEncoding="UTF-8"%>
2. <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
3. <c:forEach items="${users}" var="user">
4. ${user.value.username}----${user.value.nickname}----${user.value.password}----${user.value.email}
5. <br/>
6. </c:forEach>
7. <a href="<%=request.getContextPath()%>/user/add">继续添加新用户</a>
1. package com.jadyer.model;
2.
3. import javax.validation.constraints.Size;
4.
5. import org.hibernate.validator.constraints.Email;
6. import org.hibernate.validator.constraints.NotEmpty;
7.
8. /**
9. * User
10. * @see ===================================================================================================
11. * @see JSR303是JavaEE6中的一项子规范,叫做BeanValidation,它的官方参考实现是hibernate-validator
12. * @see BeanValidation现在一共有两个规范:BeanValidation1.0(即JSR303)和BeanValidation1.1(即JSR349)
13. * @see BeanValidation的官网是http://beanvalidation.org/
14. * @see 关于JSR303的详细说明,请参考http://jcp.org/en/jsr/detail?id=303
15. * @see 关于JSR349的详细说明,请参考http://jcp.org/en/jsr/detail?id=349
16. * @see ===================================================================================================
17. * @see JSR303规范主要用于对JavaBean中的字段的值的验证,使得验证逻辑从业务代码中脱离出来
18. * @see JSR303定义了基于注解方式的JavaBean验证元数据模型和API,也可通过XML进行元数据定义,但注解会覆盖XML的定义
19. * @see JSR303主要是对JavaBean进行验证,而没有指定方法级别(参数or返回值)、依赖注入等验证,因此催生了JSR349规范
20. * @see JSR349规范目前处于草案状态,它主要支持依赖注入的验证和方法级别的验证(方法的参数和返回值)
21. * @see Spring3.1目前已经完全支持依赖注入验证和方法级别的验证了,只不过不是原生的(JSR349规范还是草案嘛)
22. * @see 关于这个的详细说明,可以参考此爷的文章http://www.iteye.com/topic/1123007
23. * @see ===================================================================================================
24. * @see 另外,Struts2已经可以很完美的和JSR303整合到一起了,呵呵,很是叫我欣慰啊!!!!
25. * @see ===================================================================================================
26. * @see 我们这里使用的是JSR303的hibernate-validator实现,它主要需要以下三个jar包
27. * @see jboss-logging-3.1.0.CR2.jar
28. * @see validation-api-1.0.0.GA.jar
29. * @see hibernate-validator-4.3.0.Final.jar
30. * @see ===================================================================================================
31. * @author http://blog.csdn.net/jadyer
32. * @create May 12, 2012 3:00:46 AM
33. */
34. public class User {
35. @NotEmpty(message="姓名不能为空")
36. private String username;
37. private String nickname;
38. @Size(min=3, max=10, message="密码长度必须大于3小于10")
39. private String password;
40. @NotEmpty(message="邮箱不能为空")
41. @Email(message="邮箱格式不正确") //也可通过@Pattern(regexp="")书写正则来判断,二者都是JSR303规范中的
42. private String email;
43.
44. public User() {}
45. public User(String username, String nickname, String password, String email) {
46. this.username = username;
47. this.nickname = nickname;
48. this.password = password;
49. this.email = email;
50. }
51.
52. public String getUsername() {
53. return username;
54. }
55. public void setUsername(String username) {
56. this.username = username;
57. }
58. public String getNickname() {
59. return nickname;
60. }
61. public void setNickname(String nickname) {
62. this.nickname = nickname;
63. }
64. public String getPassword() {
65. return password;
66. }
67. public void setPassword(String password) {
68. this.password = password;
69. }
70. public String getEmail() {
71. return email;
72. }
73. public void setEmail(String email) {
74. this.email = email;
75. }
76. }
1. package com.jadyer.controller;
2.
3. import java.util.HashMap;
4. import java.util.Map;
5.
6. import javax.validation.Valid;
7.
8. import org.springframework.stereotype.Controller;
9. import org.springframework.ui.Model;
10. import org.springframework.validation.BindingResult;
11. import org.springframework.web.bind.annotation.RequestMapping;
12. import org.springframework.web.bind.annotation.RequestMethod;
13.
14. import com.jadyer.model.User;
15.
16. /**
17. * @see ====================================================================================
18. * @see SpringMVC中借助JSR303规范进行表单验证
19. * @see 第一步:在实体类中针对需要验证的属性,进行Annotation配置
20. * @see 第二步:在Controller的方法参数前使用@Valid开启JSR303验证,并添加BindingResult参数
21. * @see BindingResult承载着JSR303验证时所产生的message,可据此进行判断验证结果
22. * @see 第三步:判断BindingResult中是否装载了JSR303验证的message,有则转到前台页面显示出来
23. * @see 第四步:前台页面中使用<form:errors path="username"/>打印JSR303的message信息
24. * @see ====================================================================================
25. * @see SpringMVC与sitemesh2.4无缝整合
26. * @see 第一步:拷贝sitemesh-2.4.jar到工程中
27. * @see 第二步:在web.xml中配置com.opensymphony.sitemesh.webapp.SiteMeshFilter
28. * @see 第三步:创建并编辑sitemesh配置文件decorators.xml
29. * @see 第四步:创建并编辑/WEB-INF/sitemesh/basic.jsp
30. * @see ====================================================================================
31. * @author http://blog.csdn.net/jadyer
32. * @create May 12, 2012 3:20:46 AM
33. */
34. @Controller
35. @RequestMapping("/user")
36. public class UserController {
37. private final static Map<String,User> users = new HashMap<String,User>();
38.
39. @RequestMapping(value="/add", method=RequestMethod.GET)
40. public String addUser(Model model){
41. model.addAttribute(new User());
42. return "user/add";
43. }
44. @RequestMapping(value="/add", method=RequestMethod.POST)
45. public String addUser(@Valid User user, BindingResult binding){
46. //该方法若有其它参数,应写成这样addUser(@Valid User user, BindingResult binding, String job)
47. //就是说,这里一定要把BindingResult放在待验证对象(@Valid User user)参数的后面,否则会报错
48. if(binding.hasErrors()){
49. return "user/add";
50. }
51. users.put(user.getUsername(), user);
52. return "redirect:/user/list";
53. }
54.
55. @RequestMapping("/list")
56. public String list(Model model){
57. model.addAttribute("users", users);
58. return "user/list";
59. }
60. }
本示例的访问地址是http://127.0.0.1:8080/SpringMVC_study/user/add