作者: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上下文配置




  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对象



  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. 国际化资源文件





5. 控制层




下面这张图是从其他文章中截取的,主要用于说明:@Valid与BindingResult之间的关系;

  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标签:

在前台显示错误:


  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. 测试



8. 其他

参考链接:
淘宝源程序下载(可直接运行):




附件列表

【Spring学习笔记-MVC-10】Spring MVC之数据校验的更多相关文章

  1. 【Spring学习笔记-MVC-4】SpringMVC返回Json数据-方式2

    <Spring学习笔记-MVC>系列文章,讲解返回json数据的文章共有3篇,分别为: [Spring学习笔记-MVC-3]SpringMVC返回Json数据-方式1:http://www ...

  2. 【Spring学习笔记-MVC-3】SpringMVC返回Json数据-方式1

    <Spring学习笔记-MVC>系列文章,讲解返回json数据的文章共有3篇,分别为: [Spring学习笔记-MVC-3]SpringMVC返回Json数据-方式1:http://www ...

  3. 【Spring学习笔记-MVC-7】Spring MVC模型对象-模型属性讲解

    作者:ssslinppp       来自为知笔记(Wiz) 附件列表 处理模型数据.png

  4. 【Spring学习笔记-MVC-14】Spring MVC对静态资源的访问

    作者:ssslinppp       参考链接: http://www.cnblogs.com/luxh/archive/2013/03/14/2959207.html  http://www.cnb ...

  5. 【Spring学习笔记-MVC-16】Spring MVC之重定向-解决中文乱码

    概述 spring MVC框架controller间跳转,需重定向,主要有如下三种: 不带参数跳转:形如:http://localhost:8080/SpringMVCTest/test/myRedi ...

  6. 【Spring学习笔记-MVC-15】Spring MVC之异常处理

    作者:ssslinppp       1. 描述 在J2EE项目的开发中,不管是对底层的数据库操作过程,还是业务层的处理过程,还是控制层的处理过程,都不可避免会遇到各种可预知的.不可预知的异常需要处理 ...

  7. 【Spring学习笔记-MVC-13】Spring MVC之文件上传

    作者:ssslinppp       1. 摘要 Spring MVC为文件上传提供了最直接的支持,这种支持是通过即插即用的MultipartResolve实现的.Spring使用Jakarta Co ...

  8. 【Spring学习笔记-MVC-12】Spring MVC视图解析器之ResourceBundleViewResolver

    场景 当我们设计程序界面的时候,中国人希望界面是中文,而美国人希望界面是英文. 我们当然希望后台代码不需改变,系统能够通过配置文件配置,来自己觉得是显示中文界面还是英文界面. 这是,Spring mv ...

  9. Spring学习笔记 7.1 Spring MVC起步

    7.1.1 跟踪Spring MVC的请求请求首先到达DispatcherServlet(DispatcherServlet是Spring MVC中的前端控制器):DispatcherServlet的 ...

随机推荐

  1. 【python】判断值是否在list和set的对比以及set的实现原理

    判断值是否在set集合中的速度明显要比list快的多, 因为查找set用到了hash,时间在O(1)级别. 假设listA有100w个元素,setA=set(listA)即setA为listA转换之后 ...

  2. vector中erase用法注意事项

    以前就发现了vector中的erase方法有些诡异(^_^),稍不注意,就会出错.今天又一次遇到了,就索性总结一下,尤其是在循环体中用erase时,由于vector.begin() 和vector.e ...

  3. L1-037 A除以B

    真的是简单题哈 —— 给定两个绝对值不超过100的整数A和B,要求你按照“A/B=商”的格式输出结果. 输入格式: 输入在第一行给出两个整数A和B(−100≤A,B≤100),数字间以空格分隔. 输出 ...

  4. 增量打包DOC版

    压缩zip的命令有的系统没有的自己去下载一个,否则关闭压缩zip的命令. 有需要的自行更改,这是满足我需求的. 执行 publish.bat 即可,当然需要将文件清单写好放在 resources.tx ...

  5. SharePoint 2010 Ribbon with wrong style in Chrome and Safari

    When we add custom ribbon to SharePoint 2010, it may display well in IE but not in Chrome and Safari ...

  6. [翻译]HTTP--一个应用级的协议

    原文地址:HTTP — an Application-Level Protocol 简介 在不丹,当人们见面时,他们通常用“你身体还好吗?”互相打招呼.在日本,根据当时的情形,人们可能会互相鞠躬.在阿 ...

  7. select * from v$reserved_words

    select * from v$reserved_words 查询库中所有关键字

  8. Ubuntu使用Remastersys封装制作系统ISO镜像

    首先下载Remastersys的Deb软件包 链接:http://pan.baidu.com/s/1i3tYPKT 密码:qvyd 使用命令强制安装 dpkg --force-all -i remas ...

  9. js 压缩 预览 上传图片

    com.js export const compressImage=function (files,fn,preCallbackFn,i) { let newfile = files.files[0] ...

  10. 【转载】Java枚举类型的使用

    枚举类型概念 package com.lxq.enumm; public class EnumDemoOne { private enum InnerEnum { RED, GREEN, YELLOW ...