通常情况下,数据验证都分为前台验证,后台验证。并且前台JS验证是肯定有的,那么其实验证的错误信息根本不必通过后台传过去,哪怕就是想国际化,前台JS也能够胜任。

如果前台验证足够了,那么如果还有不正确的信息传到后台去,极有可能是通过非法手段。那么我对这些信息也不必客气,直接拒接就行了,连错误信息都不必发。 基于这个思想,

后台验证可以省掉很多东西。

我们现在使用Hibernate的那一套验证,必须引入Hibernate-validator的jar包。到Maven Repository 去找就行了。如果还找不到,拿到百度云里找吧

现有POJO类:

  1. import java.lang.reflect.Field;
  2.  
  3. import org.hibernate.validator.constraints.Email;
  4. import org.hibernate.validator.constraints.NotEmpty;
  5.  
  6. public class People {
  7.  
  8. private int id;
  9.  
  10. @NotEmpty
  11. private String name;
  12.  
  13. @Email
  14. private String address;
  15.  
  16. private int age;
  17.  
  18. public final int getId() {
  19. return id;
  20. }
  21.  
  22. public final void setId(int id) {
  23. this.id = id;
  24. }
  25.  
  26. public final String getName() {
  27. return name;
  28. }
  29.  
  30. public final void setName(String name) {
  31. this.name = name;
  32. }
  33.  
  34. public final String getAddress() {
  35. return address;
  36. }
  37.  
  38. public final void setAddress(String address) {
  39. this.address = address;
  40. }
  41.  
  42. public final int getAge() {
  43. return age;
  44. }
  45.  
  46. public final void setAge(int age) {
  47. this.age = age;
  48. }
  49.  
  50. @Override
  51. public String toString() {
  52. return "People [id=" + id + ", name=" + name + ", address=" + address
  53. + ", age=" + age + "]";
  54. }
  55.  
  56. public People set(String name, Object obj) {
  57. try {
  58. Field f = this.getClass().getDeclaredField(name);
  59. f.setAccessible(true);
  60. f.set(this, obj);
  61. } catch (NoSuchFieldException | SecurityException
  62. | IllegalArgumentException | IllegalAccessException e) {
  63. e.printStackTrace();
  64. }
  65. return this;
  66. }
  67.  
  68. }

可以看到在属性name上有@NotEmpty,在属性address上有@Email(当然这是假装的)。

在Controller中有方法:

  1. @RequestMapping(value="/add",method=RequestMethod.POST)
  2. public String add(@Valid People p,BindingResult result, HttpServletRequest request) {
  3. if(result.hasErrors())
  4. return "error";
  5. this.peopleService.add(p);
  6. return "people/detail";
  7. }

注意在参数p之前有注解@Valid,并且在p之后紧接着就是BindingResult result。BindingResult result一定要紧跟着People p。

这样如果有错误,通过代码 if(result.hasErrors()) return "error"; 直接返回到error界面,error界面甚至不必存在。。。

另外,这样还有好处,People中 age的类型是int。如果传参数是age是一个不可以转换为int的字符串怎么办?

哈哈,这时 result.hasErrors() 的返回值也是true,也就是还是会返回error界面。

补充一点:非空验证是用的最多的,你会看到有 @NotEmpty,@NotNull,@NotBlank 三个差不多的注解

1.@NotNull 用于任何引用类型,验证是不是null

2.@NotEmpty。 用于CharSequence,Collection, Map and Arrays,验证不是null并且CharSequence长度不是0,collection,Map,Array大小不是0

3.@NotBlank。用于CharSequence。 验证是不是null;如果不是null,那么trim之后验证长度是不是0

所有日常验证字符串时,还是使用@NotBlank吧

关于可以有哪些验证的注解,直接网上copy的。

注解

适用的数据类型

说明

@AssertFalse

Boolean, boolean

验证注解的元素值是false

@AssertTrue

Boolean, boolean

验证注解的元素值是true

@DecimalMax(value=x)

BigDecimal, BigInteger, String, byte,short, int, long and the respective wrappers of the primitive types. Additionally supported by HV: any sub-type of Number andCharSequence.

验证注解的元素值小于等于@ DecimalMax指定的value值

@DecimalMin(value=x)

BigDecimal, BigInteger, String, byte,short, int, long and the respective wrappers of the primitive types. Additionally supported by HV: any sub-type of Number andCharSequence.

验证注解的元素值小于等于@ DecimalMin指定的value值

@Digits(integer=整数位数, fraction=小数位数)

BigDecimal, BigInteger, String, byte,short, int, long and the respective wrappers of the primitive types. Additionally supported by HV: any sub-type of Number andCharSequence.

验证注解的元素值的整数位数和小数位数上限

@Future

java.util.Date, java.util.Calendar; Additionally supported by HV, if theJoda Time date/time API is on the class path: any implementations ofReadablePartial andReadableInstant.

验证注解的元素值(日期类型)比当前时间晚

@Max(value=x)

BigDecimal, BigInteger, byte, short,int, long and the respective wrappers of the primitive types. Additionally supported by HV: any sub-type ofCharSequence (the numeric value represented by the character sequence is evaluated), any sub-type of Number.

验证注解的元素值小于等于@Max指定的value值

@Min(value=x)

BigDecimal, BigInteger, byte, short,int, long and the respective wrappers of the primitive types. Additionally supported by HV: any sub-type of CharSequence (the numeric value represented by the char sequence is evaluated), any sub-type of Number.

验证注解的元素值大于等于@Min指定的value值

@NotNull

Any type

验证注解的元素值不是null

@Null

Any type

验证注解的元素值是null

@Past

java.util.Date, java.util.Calendar; Additionally supported by HV, if theJoda Time date/time API is on the class path: any implementations ofReadablePartial andReadableInstant.

验证注解的元素值(日期类型)比当前时间早

@Pattern(regex=正则表达式, flag=)

String. Additionally supported by HV: any sub-type of CharSequence.

验证注解的元素值与指定的正则表达式匹配

@Size(min=最小值, max=最大值)

String, Collection, Map and arrays. Additionally supported by HV: any sub-type of CharSequence.

验证注解的元素值的在min和max(包含)指定区间之内,如字符长度、集合大小

@Valid

Any non-primitive type(引用类型)

验证关联的对象,如账户对象里有一个订单对象,指定验证订单对象

@NotEmpty

CharSequence,Collection, Map and Arrays

验证注解的元素值不为null且不为空(字符串长度不为0、集合大小不为0)

@Range(min=最小值, max=最大值)

CharSequence, Collection, Map and Arrays,BigDecimal, BigInteger, CharSequence, byte, short, int, long and the respective wrappers of the primitive types

验证注解的元素值在最小值和最大值之间

@NotBlank

CharSequence

验证注解的元素值不为空(不为null、去除首位空格后长度为0),不同于@NotEmpty,@NotBlank只应用于字符串且在比较时会去除字符串的空格

@Length(min=下限, max=上限)

CharSequence

验证注解的元素值长度在min和max区间内

@Email

CharSequence

验证注解的元素值是Email,也可以通过正则表达式和flag指定自定义的email格式

更多信息请参考官方文档:http://docs.jboss.org/hibernate/validator/4.3/reference/en-US/html/validator-usingvalidator.html

spring 4.0 注解数据验证1的更多相关文章

  1. spring 4.0 注解数据验证2

    在spring 4.0 注解数据验证1中有基本的数据验证方法.还是那个POJO: package com.suyin.pojo; import java.lang.reflect.Field; imp ...

  2. Spring 3.0 注解

    原文 :http://www.blogjava.net/ashutc/archive/2011/04/14/348270.html 另两 参考博客 : http://kingtai168.iteye. ...

  3. Spring 3.0 注解注入详解

    国内私募机构九鼎控股打造APP,来就送 20元现金领取地址:http://jdb.jiudingcapital.com/phone.html内部邀请码:C8E245J (不写邀请码,没有现金送)国内私 ...

  4. spring(7)--注解式控制器的数据验证、类型转换及格式化

    7.1.简介 在编写可视化界面项目时,我们通常需要对数据进行类型转换.验证及格式化. 一.在Spring3之前,我们使用如下架构进行类型转换.验证及格式化: 流程: ①:类型转换:首先调用Proper ...

  5. Spring MVC 数据验证——validate注解方式

    1.说明 学习注解方式之前,应该先学习一下编码方式的spring注入.这样便于理解验证框架的工作原理.在出错的时候,也能更好的解决这个问题.所以本次博客教程也是基于编码方式.仅仅是在原来的基础加上注解 ...

  6. Hibernate Validation,Spring mvc 数据验证框架注解

    1.@NotNull:不能为 Null,但是可以为Empty:用在基本数据类型上. @NotNull(message="{state.notnull.valid}", groups ...

  7. Spring MVC 3.0.5+Spring 3.0.5+MyBatis3.0.4全注解实例详解(四)

    这一章大象将详细分析web层代码,以及使用Spring MVC的注解及其用法和其它相关知识来实现控制器功能.     之前在使用Struts2实现MVC的注解时,是借助struts2-conventi ...

  8. Spring MVC 使用介绍(十三)数据验证 (一)基本介绍

    一.消息处理功能 Spring提供MessageSource接口用于提供消息处理功能: public interface MessageSource { String getMessage(Strin ...

  9. Spring MVC 数据验证——validate编码方式

    1.导入jar包 validation-api-1.0.0.GA.jar这是比較关键的一个jar包,主要用于解析注解@Valid. hibernate-validator-4.3.2.Final.ja ...

随机推荐

  1. Java实现将一段汉字变成unicode码

    public class T { public static void main(String[] args) { String s = "java 中文编码"; System.o ...

  2. nginx别名配置,状态配置,include优化

    一.nginx帮助参数 下面是关于/application/nginx/sbin/nginx 的参数帮助 [root@A conf]# /application/nginx/sbin/nginx -h ...

  3. Oracle数据库设计规范建议

    Oracle数据库设计规范建议 1 目的 本规范的主要目的是希望规范数据库设计,尽量提前避免由于数据库设计不当而产生的麻烦:同时好的规范,在执行的时候可以培养出好的习惯,好的习惯是软件质量的很好的保证 ...

  4. 算法(Algorithms)第4版 练习 2.1.27

    package com.qiusongde; import edu.princeton.cs.algs4.StdOut; public class Exercise2127 { public stat ...

  5. Struts2 内核之我见

    Struts2 内核之我见 完整分析 Struts2 内核中文文档 本文首先探讨了 Struts2 核心控制器的源码,以帮助解读 Struts2 的工作流程.接着讲解相关外围类.最后对 Struts ...

  6. PHP中有多态么

    PHP中有多态么 一.总结 一句话总结:封装是类的构建过程,php具有:php也具有继承的特性.唯独这个多态,php体现的十分模糊.原因是php是弱类型语言. php不具有像java那种清晰的多态,不 ...

  7. 一個在WCF學習中的小教訓(本人非科班菜鳥,此經驗無參考價值,衹是自己的經驗記錄)

    1.关于“ServiceHost 仅支持类服务类型”的解决:   Service属性必须执行,不是接口. 改为下图所示: 解决! (注:按朱哥的方法WCF已经可以通信---截至今天的11:11(例子在 ...

  8. 创建第一个Servlet并定制Sevlet模板

    我们已经为eclipse配好了Tomcat服务器,创建了Web工程,现在是时候该创建一个Servlet向世界问好了! 第一步:创建一个Web工程,选中”src“文件夹 -->单击右键,鼠标移到” ...

  9. hbase_异常_01_Hbase: Failed to become active master

    一.异常现象 启动hbase之后,抛出异常,异常信息如下: master.HMaster: Failed to become active master hbase java.net.ConnectE ...

  10. 宽度显示banner

    今天解决了一个以前解决不了的问题,所以就想找博客园记录一些笔记. ……以前也遇到过这种满屏banner不知道怎么做的问题,问老师老师也说不出个所以然,百度搜了好几条 也不太满意... 所以就开始尝试摸 ...