牛骨文教育服务平台(让学习变的简单)
博文笔记

Hibernate-validator校验框架

创建时间:2016-09-15 投稿人: 浏览次数:22226

Validator开发者使用手册,适用后台校验功能的开发参考。

1.1. 背景

在我们日常后台的开发中,涉及到很多的字段验证,一般普通的验证框架就基本上可以满足日常的开发需求,但有一些情况,这些普通的验证框架无法达到要求,例如,我们必须对验证的属性进行分组,于是就产生了我们的Validator验证框架。当然,我们的验证框架不仅仅只提供了分组的功能。

《Hibernate Validator - 5.1.0 - 英文版.pdf》

3.1. 工作模式和配置模式

Validator提供两种工作模式:

1、普通模式

2、快速失败返回模式

默认的工作模式为快速失败返回模式,一旦发现校验失败项,立即返回。普通模式在测试时期可以使用,可以对全部的校验项进行完整的校验(校验组序列,以及基于校验组序列的其他配置无效),通过修改配置文件中的校验模式,从而实现工作模式的自由切换。开发人员无需关心其中的原理和过程。

两种配置模式:Annotation和Xml文件(此处略)。

推荐使用Annotation注解模式。

工作模式配置如下:

validator.fail_fast:快速失败返回模式(只要有一个验证失败,则返回异常)

validator.normal:普通模式(会校验完所有的属性,然后返回所有的验证失败信息)

3.2. 校验功能

Validator校验框架按照Bean Validation的规范,使用了Hibernate Validatior框架。当前通过测试验证的可以支持的功能有:

1、内置注解校验

2、对象图级联校验

3、校验组分组校验

4、校验组序列

5、自定义默认校验组功能

6、自定义智能默认校验组功能

7、自定义校验注解

8、类校验——类属性的关联校验

此外,框架还内嵌了一些非法校验的功能,比如输入的校验对象为null,或者指定的对象的属性值错误,都会自行抛出异常。

4.1. Validator的jar包

目前,Validator的版本为2.0.0,后面可能会涉及到版本的更新。原始工程为Maven工程,使用的时候,只需要导入Validator依赖的pom文件以及进行简单的配置即可。

<dependency>

<groupId>com.travelsky.common</groupId>

<artifactId>validate</artifactId>

<version>2.0.0</version>

</dependency>

4.2. Validator的配置文件

配置文件可以从jar包里面获取,使用的时候,直接加入类路径下即可。附件部分给出了Validator依赖的pom文件。配置文件如下:

<bean id="baseValidator" class="com.travelsky.common.validator.BaseValidator">

<property name="validatorMode">

        <!-- 校验器的工作模式:

validator.fail_fast:快速失败返回模式(只要有一个验证失败,则返回异常)

validator.normal:普通模式(会校验完所有的属性,然后返回所有的验证失败信息)

        -->

<value>validator.normal</value>

</property>

</bean>

4.3. Validator接口

使用Validator的校验框架非常的简单,只需要注入Validator接口即可:

@Autowired

private Validator validator;

4.4. Validator中的方法

Validator提供了6个校验接口供开发人员使用:

1、<T> void validate(T object) throws Exception

用途:校验一个对象的默认校验组的属性。

2、<T> void validate(T object, Class<?>... groups) throws Exception

用途:校验一个对象的指定的一个或多个校验组的属性。

3、<T> void validateProperty(T object, String propertyName) throws Exception

用途:校验一个对象的默认校验组的一个指定的属性值。

4、<T> void validateProperty(T object, String propertyName, Class<?>... groups) throws Exception

用途:校验一个对象指定校验组中的一个指定的属性值。

5、<T> void validateValue(Class<T> beanType, String propertyName, Object value) throws Exception

用途:校验一个value是否符合指定类的默认校验组下的某一个属性值。

6、<T> void validateValue(Class<T> beanType, String propertyName, Object value, Class<?>... groups) throws Exception

用途:校验一个value是否符合指定类的指定校验组下的某一个属性值。

4.5. 测试类

大家可以从工程源码的测试目录中,找到测试类,所有的测试类都可以正常运行,并加入了详细的注释说明。

本章节提供了各种校验功能具体的开发方法,基本能够满足开发人员所有 的校验需求。(所有的实体类省略了get和set方法)

5.1. 内置注解校验

适用场景:简单的单属性的校验。

内置的校验注解共分为三种:Bean Validation内置的校验注解和Hibernate Validator拓展的校验注解以及框架自带的校验注解。推荐大家首先考虑使用这些注解,简单易用。

使用方法:

public class RangeModel {

@Length(min=5, max=17)

private String length;

@Size(min=1, max=3)

private String age;

@Range(min=150,max=250)

private int high;

5.1.1. Bean Validator内置的注解

Annotation

支持的数据类型

作用

Hibernate metadata impact

@AssertFalse

Boolean, boolean

判断关联属性是否为布尔值false

没有

@AssertTrue

Boolean, boolean

Checks that the annotated element istrue.

没有

@DecimalMax

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

被注解的值必须不大于约束中指定的最大值. 这个约束的参数是一个通过BigDecimal定义的最大值的字符串表示.

没有

@DecimalMin

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

被注解的值必须不小于约束中指定的最小值. 这个约束的参数是一个通过BigDecimal定义的最小值的字符串表示.

没有

@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.

校验整数位数和小数位数

对应的数据库表字段会被设置精度(precision)和准度(scale).

@Future

java.util.Date, java.util.Calendar; Additionally supported by HV, if the Joda Time date/time API is on the class path: any implementations of ReadablePartial and ReadableInstant.

检查给定的日期是否比现在晚.

没有

@Max

BigDecimal, BigInteger, byte, short, int, longand the respective wrappers of the primitive types. Additionally supported by HV: String(the numeric value represented by a String is evaluated), any sub-type of Number.

检查该值是否小于或等于约束条件中指定的最大值.

会给对应的数据库表字段添加一个check的约束条件.

@Min

BigDecimal, BigInteger, byte, short, int, longand the respective wrappers of the primitive types. Additionally supported by HV: String(the numeric value represented by a String is evaluated), any sub-type of Number.

检查该值是否大于或等于约束条件中规定的最小值.

会给对应的数据库表字段添加一个check的约束条件.

@NotNull

Any type

Checks that the annotated value is notnull.

对应的表字段不允许为null.

@Null

Any type

Checks that the annotated value is null.

没有

@Past

java.util.Date, java.util.Calendar; Additionally supported by HV, if the Joda Time date/time API is on the class path: any implementations of ReadablePartial and ReadableInstant.

检查注解对象中的值表示的日期比当前早.

没有

@Pattern(regex=, flag=)

String

检查该字符串是否能够在match指定的情况下被regex定义的正则表达式匹配.

没有

@Size(min=, max=)

String, Collection, Map and arrays

校验对象的size。本文作者认为前提是该对象有size()方法,String除外。

对应的数据库表字段的长度会被设置成约束中定义的最大值.

@Valid

Any non-primitive type

递归的对关联对象进行校验, 如果关联对象是个集合或者数组, 那么对其中的元素进行递归校验,如果是一个map,则对其中的值部分进行校验.

没有

5.1.2. Hibernate Validator拓展的注解

Annotation

支持的数据类型

作用

Hibernate metadata impact

@CreditCardNumber

String

校验信用卡号码

没有

@Email

String

校验邮件地址

没有

@Length(min=, max=)

String

功能同@Size,但是只支持String类型

对应的数据库表字段的长度会被设置成约束中定义的最大值.

@NotBlank

String

不为null,不为空值,不为全空格。功能强大于@NotEmpty

没有

@NotEmpty

String,Collection,Map and arrays

校验是否为null或者为空值。功能强于@NotNull

没有

@Range(min=, max=)

BigDecimal,BigInteger,String, byte,short, int,long and the respective wrappers of the primitive types

判断数值的范围,不仅支持数值类型,还支持字符串、字节等等类型

没有

@SafeHtml(whitelistType=, additionalTags=)

CharSequence

无使用价值

没有

@ScriptAssert(lang=, script=, alias=)

Any type

无使用价值

没有

@URL(protocol=, host=, port=, regexp=, flags=)

String

Checks if the annotated string is a valid URL according to RFC2396. If any of the optional parameters protocol, host or port are specified, the corresponding URL fragments must match the specified values. The optional parametersregexp and flags allow to specify an additional regular expression (including regular expression flags) which the URL must match.

没有

5.1.3. Validator框架拓展注解

Annotation

支持的数据类型

作用

@NotEmptyPattern

String

在字符串不为空的情况下,验证是否匹配正则表达式

@ListStringPattern

List<String>

验证集合中的字符串是否满足正则表达式

@DateValidator

String

验证日期格式是否满足正则表达式,Local为ENGLISH

@DateFormatCheckPattern

String

验证日期格式是否满足正则表达式,Local为自己手动指定

5.2. 对象图级联校验

Validator不仅能够校验单个实例对象,还可以校验完整的对象图。对于实例中的对象成员属性,注解上@Valid,就可以被关联校验。

声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。