javaweb 服务端需要对请求数据进行校验,不过编写校验代码繁琐费时重复劳动。发现可以使用Bean Validation框架进行数据校验,在此整理了一个快速使用教程。
基本使用
pom文件添加:
<dependency>
<artifactId>hibernate-validator</artifactId>
<groupId>org.hibernate</groupId>
<version>6.0.16.Final</version>
</dependency>
javaBean代码:
public class User {
private Integer userId;
@NotEmpty(message = "用户名称不能为空")
@Size(min=4,max = 16,message = "用户名称长度在4-16字符之间")
private String userName;
@NotNull(message = "城市不能为空")
private Integer cityId;
@NotEmpty(message = "手机号不能为空")
@Pattern(regexp = "\\d{8,14}",message = "手机号格式不对")
private String phone;
//get and set
}
多层对象校验, 在成员变量使用注解@Valid
public class UserInfo{
@Valid
private User user;
//get set
}
校验:
ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
Validator validator = validatorFactory.getValidator();
//装载校验对象并进行校验
Set<ConstraintViolation<T>> resultSet = validator.validate(user);
for (ConstraintViolation<T> violation : resultSet) {
logger.error(violation.getMessage());
}
spring mvc整合使用校验
@PostMapping("userAdd")
public String userAdd(@Valid User user,@Valid UserInfo userInfo,BindingResult result) throws Exception {
//校验结果封装在 BindingResult对象里
if (result != null && result.hasErrors()) {
return result.getAllErrors().stream().findFirst().get().getDefaultMessage();
}
//........
return "ok";
}
注解类型
@Null | 验证 元素为null |
@NotNull | 验证 元素为非null |
@AssertTrue | 验证 元素为true |
@AssertFalse | 验证 元素为false |
@Min | 验证 元素大于等于@Min指定的value值 |
@Max | 验证 元素小于等于@max指定的value值 |
@NotBlank | 验证 元素不为 null或者 长度为0的字符 |
@NotEmpty | 验证 元素值不为 null ,字符串长度不为0、集合大小不为0 |
@DecimalMax | 验证 元素小于等于@ DecimalMax指定的value值 |
@DecimalMin | 验证 元素大于等于@ DecimalMin指定的value值 |
@Digits | 验证注解的元素值的整数位数(integer)和小数位数(fraction)上限 |
验证 email格式 | |
@Future | 验证 日期元素 晚于当前时间 |
@FutureOrPresent | 验证 日期元素 是等于或晚于当前时间 |
@Negative | 验证 元素为负数 |
@NegativeOrZero | 验证 元素为负数或者0 |
@Past | 验证 日期元素 早于当前时间 |
@PastOrPresent | 验证 日期元素 等于或早于当前时间 |
@Pattern | 验证 元素 是否匹配正则表达式 |
@Positive | 验证 元素为正数 |
@PositiveOrZero | 验证 元素为正数或者0 |
@Size | 验证 元素在min和max(包含)指定区间之内,如字符长度、集合大小 |
分组和顺序验证
有时候新增和修改需要校验不同的字段,需要使用分组校验功能。并且在使用中需要进行自定义的顺序校验
定义分组接口和顺序:
@GroupSequence({ValidateGroups.A.class,
ValidateGroups.B.class,
ValidateGroups.C.class,
ValidateGroups.D.class,
ValidateGroups.E.class})
public interface ValidateGroups {
public interface A{ }
public interface B{ }
public interface C{ }
public interface D{ }
public interface E{ }
}
javaBean 代码改造:
public class User {
private Integer userId;
@NotEmpty(message = "用户名称不能为空",groups = ValidateGroups.A.class)
@Size(min=4,max = 16,message = "用户名称长度在4-16字符之间",groups = ValidateGroups.A.class)
private String userName;
@NotNull(message = "城市不能为空",groups = ValidateGroups.C.class)
private Integer cityId;
@NotEmpty(message = "手机号不能为空",groups = ValidateGroups.D.class)
@Pattern(regexp = "\\d{8,14}",message = "手机号格式不对",groups = ValidateGroups.D.class)
private String phone;
//get and set
}
spring mvc controller 改成用@Validated注解进行校验,并指定分组名称
@PostMapping("userAdd")
public String userAdd(@Validated({ValidateGroups.class}) User user, BindingResult result) throws Exception {
if (result != null && result.hasErrors()) {
return result.getAllErrors().stream().findFirst().get().getDefaultMessage();
}
//........
return "ok";
}