现更新地址: http://www.yiyehu.tech/archives/2019/05/23/hibernate-validator
在Maven project使用
Hibernate Validator Maven dependency
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.0.9.Final</version>
</dependency>
Maven dependencies for Unified EL reference implementation
如果没有提供EL表达式的实现,则在pom.xml中添加下面的依赖
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.el</artifactId>
<version>3.0.1-b09</version>
</dependency>
Hibernate Validator CDI portable extension Maven dependency
如果没有提供CDI(Contexts and Dependency Injection for Java,java的上下文和依赖注入),则在pom.xml中添加下面的依赖
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator-cdi</artifactId>
<version>6.0.9.Final</version>
</dependency>
###常用约束的注解
/**
* Bean Validation 中内置的 constraint
* @Null 被注释的元素必须为 null
* @NotNull 被注释的元素必须不为 null
* @AssertTrue 被注释的元素必须为 true
* @AssertFalse 被注释的元素必须为 false
* @Min(value) 被注释的元素必须是一个数字,其值必须大于等于指定的最小值
* @Max(value) 被注释的元素必须是一个数字,其值必须小于等于指定的最大值
* @DecimalMin(value) 被注释的元素必须是一个数字,其值必须大于等于指定的最小值
* @DecimalMax(value) 被注释的元素必须是一个数字,其值必须小于等于指定的最大值
* @Size(max=, min=) 被注释的元素的大小必须在指定的范围内
* @Digits (integer, fraction) 被注释的元素必须是一个数字,其值必须在可接受的范围内
* @Past 被注释的元素必须是一个过去的日期
* @Future 被注释的元素必须是一个将来的日期
* @Pattern(regex=,flag=) 被注释的元素必须符合指定的正则表达式
* Hibernate Validator 附加的 constraint
* @NotBlank(message =) 验证字符串非null,且长度必须大于0
* @Email 被注释的元素必须是电子邮箱地址
* @Length(min=,max=) 被注释的字符串的大小必须在指定的范围内
* @NotEmpty 被注释的字符串的必须非空
* @Range(min=,max=,message=) 被注释的元素必须在合适的范围内
* @URL 被注释的元素必须是一个有效的URL
*/
#####1.限制参数不为空的区别
@NotEmpty
Asserts that the annotated string, collection, map or array is not null or empty.
被注释的string, collection, map or array不为 null 不为空
@NotBlank
Validate that the annotated string is not null or empty. The difference to NotEmpty is that trailing whitespaces are getting ignored.
用于字符串,相比较@NotEmpty而言,@NotBlank会忽略字符串尾部的空格
@NotNull
The annotated element must not be null. Accepts any type.
支持任何类型。
#####2.实例
/**
* 用户ID
*/
@NotNull
private Long userId;
/**
* 收货人姓名
*/
@Length(max=20, message="用户名长度超出20")
private String userName;
/**
* 收货人地址
*/
@Length(max=200, message="收货人地址长度超出200")
private String userAdress;
/**
* 收货人手机
*/
@NotBlank
@Pattern(regexp="^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$", message="手机号格式不正确")
private String userMobile;
/**
* 云存储key
*/
@URL(message="无效的URL地址")
private String pathKey;
###验证约束方法1
Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
/**
*@Param object object to validate
*@Param groups the group or list of groups targeted for validation (defaults to Default)
*/
Set<ConstraintViolation<Object>> constraintViolations = validator.validate(object, groups);
if (!constraintViolations.isEmpty()) {
StringBuilder msg = new StringBuilder();
for(ConstraintViolation<Object> constraint: constraintViolations){
msg.append(constraint.getMessage()).append("<br>");
}
throw new RRException(msg.toString());//对RRException进行全局处理
}