【Spring学习笔记-MVC-10】Spring MVC之数据校验

作者:ssslinppp      

1.准备

这里我们采用Hibernate-validator来进行验证,Hibernate-validator实现了JSR-303验证框架支持注解风格的验证。首先我们要到http://hibernate.org/validator/下载需要的jar包,这里以4.3.1.Final作为演示,解压后把hibernate-validator-4.3.1.Final.jar、jboss-logging-3.1.0.jar、validation-api-1.0.0.GA.jar这三个包添加到项目中。

2. Spring MVC上下文配置
【Spring学习笔记-MVC-10】Spring MVC之数据校验_第1张图片 【Spring学习笔记-MVC-10】Spring MVC之数据校验_第2张图片

   
    
    
    
    
  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" xmlns:p="http://www.springframework.org/schema/p"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. xmlns:mvc="http://www.springframework.org/schema/mvc"
  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/context
  9. http://www.springframework.org/schema/context/spring-context-3.0.xsd
  10. http://www.springframework.org/schema/mvc
  11. http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
  12. <!-- 扫描web包,应用Spring的注解 -->
  13. <context:component-scan base-package="com.ll.web"/>
  14. <!-- 配置视图解析器,将ModelAndView及字符串解析为具体的页面,默认优先级最低 -->
  15. <bean
  16. class="org.springframework.web.servlet.view.InternalResourceViewResolver"
  17. p:viewClass="org.springframework.web.servlet.view.JstlView"
  18. p:prefix="/jsp/"
  19. p:suffix=".jsp" />
  20. <!-- 设置数据校验、数据转换、数据格式化 -->
  21. <mvc:annotation-driven validator="validator" conversion-service="conversionService"/>
  22. <!-- 数据转换/数据格式化工厂bean -->
  23. <bean id="conversionService"
  24. class="org.springframework.format.support.FormattingConversionServiceFactoryBean" />
  25. <!-- 设置校验工厂bean-采用hibernate实现的校验jar进行校验-并设置国际化资源显示错误信息 -->
  26. <bean id="validator"
  27. class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
  28. <property name="providerClass" value="org.hibernate.validator.HibernateValidator" />
  29. <!--不设置则默认为classpath下的 ValidationMessages.properties -->
  30. <property name="validationMessageSource" ref="validatemessageSource" />
  31. </bean>
  32. <!-- 设置国际化资源显示错误信息 -->
  33. <bean id="validatemessageSource"
  34. class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
  35. <property name="basename">
  36. <list>
  37. <value>classpath:valideMessages</value>
  38. </list>
  39. </property>
  40. <property name="fileEncodings" value="utf-8" />
  41. <property name="cacheSeconds" value="120" />
  42. </bean>
  43. </beans>

3. 待校验的Java对象
【Spring学习笔记-MVC-10】Spring MVC之数据校验_第3张图片
   
    
    
    
    
  1. package com.ll.model;
  2. import java.util.Date;
  3. import javax.validation.constraints.DecimalMax;
  4. import javax.validation.constraints.DecimalMin;
  5. import javax.validation.constraints.Past;
  6. import javax.validation.constraints.Pattern;
  7. import org.hibernate.validator.constraints.Length;
  8. import org.springframework.format.annotation.DateTimeFormat;
  9. import org.springframework.format.annotation.NumberFormat;
  10. public class Person {
  11. @Pattern(regexp="W{4,30}",message="{Pattern.person.username}")
  12. private String username;
  13. @Pattern(regexp="S{6,30}",message="{Pattern.person.passwd}")
  14. private String passwd;
  15. @Length(min=2,max=100,message="{Pattern.person.passwd}")
  16. private String realName;
  17. @Past(message="{Past.person.birthday}")
  18. @DateTimeFormat(pattern="yyyy-MM-dd")
  19. private Date birthday;
  20. @DecimalMin(value="1000.00",message="{DecimalMin.person.salary}")
  21. @DecimalMax(value="2500.00",message="{DecimalMax.person.salary}")
  22. @NumberFormat(pattern="#,###.##")
  23. private long salary;
  24. public Person() {
  25. super();
  26. }
  27. public Person(String username, String passwd, String realName) {
  28. super();
  29. this.username = username;
  30. this.passwd = passwd;
  31. this.realName = realName;
  32. }
  33. public String getUsername() {
  34. return username;
  35. }
  36. public void setUsername(String username) {
  37. this.username = username;
  38. }
  39. public String getPasswd() {
  40. return passwd;
  41. }
  42. public void setPasswd(String passwd) {
  43. this.passwd = passwd;
  44. }
  45. public String getRealName() {
  46. return realName;
  47. }
  48. public void setRealName(String realName) {
  49. this.realName = realName;
  50. }
  51. public Date getBirthday() {
  52. // DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
  53. // return df.format(birthday);
  54. return birthday;
  55. }
  56. public void setBirthday(Date birthday) {
  57. this.birthday = birthday;
  58. }
  59. public long getSalary() {
  60. return salary;
  61. }
  62. public void setSalary(long salary) {
  63. this.salary = salary;
  64. }
  65. @Override
  66. public String toString() {
  67. return "Person [username=" + username + ", passwd=" + passwd + "]";
  68. }
  69. }

4. 国际化资源文件

【Spring学习笔记-MVC-10】Spring MVC之数据校验_第4张图片

5. 控制层

【Spring学习笔记-MVC-10】Spring MVC之数据校验_第5张图片 【Spring学习笔记-MVC-10】Spring MVC之数据校验_第6张图片
下面这张图是从其他文章中截取的,主要用于说明:@Valid与BindingResult之间的关系;
【Spring学习笔记-MVC-10】Spring MVC之数据校验_第7张图片
   
    
    
    
    
  1. package com.ll.web;
  2. import java.security.NoSuchAlgorithmException;
  3. import javax.validation.Valid;
  4. import org.springframework.stereotype.Controller;
  5. import org.springframework.validation.BindingResult;
  6. import org.springframework.web.bind.annotation.ModelAttribute;
  7. import org.springframework.web.bind.annotation.RequestMapping;
  8. import com.ll.model.Person;
  9. /**
  10. * @author Administrator
  11. *
  12. */
  13. @Controller
  14. @RequestMapping(value = "/test")
  15. public class TestController {
  16. @ModelAttribute("person")
  17. public Person initModelAttr() {
  18. Person person = new Person();
  19. return person;
  20. }
  21. /**
  22. * 返回主页
  23. * @return
  24. */
  25. @RequestMapping(value = "/index.action")
  26. public String index() {
  27. return "regedit";
  28. }
  29. /**
  30. * 1. 在入参对象前添加@Valid注解,同时在其后声明一个BindingResult的入参(必须紧随其后),
  31. * 入参可以包含多个BindingResult参数;
  32. * 2. 入参对象前添加@Valid注解:请求数据-->入参数据 ===>执行校验;
  33. * 3. 这里@Valid在Person对象前声明,只会校验Person p入参,不会校验其他入参;
  34. * 4. 概括起来:@Valid与BindingResult必须成对出现,且他们之间不允许声明其他入参;
  35. * @param bindingResult :可判断是否存在错误
  36. */
  37. @RequestMapping(value = "/FormattingTest")
  38. public String conversionTest(@Valid @ModelAttribute("person") Person p,
  39. BindingResult bindingResult) throws NoSuchAlgorithmException {
  40. // 输出信息
  41. System.out.println(p.getUsername() + " " + p.getPasswd() + " "
  42. + p.getRealName() + " " + " " + p.getBirthday() + " "
  43. + p.getSalary());
  44. // 判断校验结果
  45. if(bindingResult.hasErrors()){
  46. System.out.println("数据校验有误");
  47. return "regedit";
  48. }else {
  49. System.out.println("数据校验都正确");
  50. return "success";
  51. }
  52. }
  53. }

6. 前台

引入Spring的form标签:

在前台显示错误:

【Spring学习笔记-MVC-10】Spring MVC之数据校验_第8张图片
   
    
    
    
    
  1. <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
  2. <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
  3. <html>
  4. <head>
  5. <title>数据校验</title>
  6. <style>
  7. .errorClass{color:red}
  8. </style>
  9. </head>
  10. <body>
  11. <form:form modelAttribute="person" action='FormattingTest.action' >
  12. <form:errors path="*" cssClass="errorClass" element="div"/>
  13. <table>
  14. <tr>
  15. <td>用户名:</td>
  16. <td>
  17. <form:errors path="username" cssClass="errorClass" element="div"/>
  18. <form:input path="username" />
  19. </td>
  20. </tr>
  21. <tr>
  22. <td>密码:</td>
  23. <td>
  24. <form:errors path="passwd" cssClass="errorClass" element="div"/>
  25. <form:password path="passwd" />
  26. </td>
  27. </tr>
  28. <tr>
  29. <td>真实名:</td>
  30. <td>
  31. <form:errors path="realName" cssClass="errorClass" element="div"/>
  32. <form:input path="realName" />
  33. </td>
  34. </tr>
  35. <tr>
  36. <td>生日:</td>
  37. <td>
  38. <form:errors path="birthday" cssClass="errorClass" element="div"/>
  39. <form:input path="birthday" />
  40. </td>
  41. </tr>
  42. <tr>
  43. <td>工资:</td>
  44. <td>
  45. <form:errors path="salary" cssClass="errorClass" element="div"/>
  46. <form:input path="salary" />
  47. </td>
  48. </tr>
  49. <tr>
  50. <td colspan="2"><input type="submit" name="提交"/></td>
  51. </tr>
  52. </table>
  53. </form:form>
  54. </body>
  55. </html>

7. 测试

输入:http://localhost:8080/SpringMVCTest/test/index.action 
【Spring学习笔记-MVC-10】Spring MVC之数据校验_第9张图片 【Spring学习笔记-MVC-10】Spring MVC之数据校验_第10张图片
8. 其他
参考链接:
http://www.cnblogs.com/ssslinppp 
http://blog.sina.com.cn/spstudy 
http://www.cnblogs.com/liukemng/p/3738055.html 
http://www.cnblogs.com/liukemng/p/3754211.html 
淘宝源程序下载(可直接运行):
http://shop110473970.taobao.com/?spm=a230r.7195193.1997079397.42.AvYpGW 
http://shop125186102.taobao.com/?spm=a1z10.1-c.0.0.SsuajD    






来自为知笔记(Wiz)


附件列表

     

    你可能感兴趣的:(【Spring学习笔记-MVC-10】Spring MVC之数据校验)