目录
1、 什么是Hibernate Validator
Hibernate Validator是Hibernate提供的一个开源框架,使用注解方式非常方便的实现服务端的数据校验。
官网:The Bean Validation reference implementation. - Hibernate Validator
hibernate Validator 是 Bean Validation 的参考实现 。
Hibernate Validator 提供了 JSR 303 规范中所有内置 constraint(约束) 的实现,除此之外还有一些附加的 constraint。
在日常开发中,Hibernate Validator经常用来验证bean的字段,基于注解,方便快捷高效。
2、 Bean校验的注解
常用注解如下:
Constraint 详细信息 @Valid 被注释的元素是一个对象,需要检查此对象的所有字段值 @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(value) 被注释的元素必须符合指定的正则表达式 被注释的元素必须是电子邮箱地址 @Length 被注释的字符串的大小必须在指定的范围内 @NotEmpty 被注释的字符串的必须非空 @Range 被注释的元素必须在合适的范围内 @NotBlank 被注释的字符串的必须非空 @URL(protocol=,host=, port=,regexp=, flags=) 被注释的字符串必须是一个有效的url @CreditCardNumber 被注释的字符串必须通过Luhn校验算法,银行卡,信用卡等号码一般都用Luhn计算合法性
3、 给User添加校验
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
</dependency>
@TableName("tb_user")
@Data
public class User {
@TableId(type = IdType.AUTO)
private Long id;
@Size(min = 4, max = 10, message = "用户名格式不正确")
private String username;
@Length(min = 4, max = 10, message = "密码格式不正确")
private String password;
private String phone;
private Date createTime;
private Date updateTime;
}
4、在controller上进行控制
如果需要自定义异常返回结果,可以这么写:
/**
* 用户注册
* BindingResult: 封装了所有字段验证失败的错误信息
*/
@PostMapping("/register")
public ResponseEntity<Void> register(@Valid User user, BindingResult result, @RequestParam("code") String code){
if(result.hasErrors()){
//取出错误信息
String errorMsg = result.getFieldErrors()
.stream()
.map(FieldError::getDefaultMessage)
.collect(Collectors.joining("|"));
//自行封装异常信息
throw new LyException(500,errorMsg);
}
userService.register(user,code);
return ResponseEntity.status(HttpStatus.CREATED).build();
}