article/java/Jsr303校验.md
2025-02-18 18:33:43 +08:00

118 lines
3.8 KiB
Markdown
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# JSR303数据校验
JSR303是Java为Bean数据合法性校验提供给的标准框架已经包含在 JavaEE6.0 中、JSR303通过在Bean 属性中标注类似 @NotNull @Max 等标准的注解指定校验规则并通过标准的验证接口对 Bean进行验证
### JSR303中含有的注解
```
@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 附加的注解
```
@NotBlank(message =) 验证字符串非null且长度必须大于0
@Email 被注释的元素必须是电子邮箱地址
@Length(min=,max=) 被注释的字符串的大小必须在指定的范围内
@NotEmpty 被注释的字符串的必须非空
@Range(min=,max=,message=) 被注释的元素必须在合适的范围内
HIbernate Validator是JSR303的一个参考实现除了支持所有标准的校验注解外另外HIbernate Validator还有JSR-380的实现
```
### @Validated @Valid 有什么区别
`@Validated` 是spring 中提供的注解用于在添加该注解的方法、类上触发bean 校验。
`@Valid` java自身的注解 用于校验嵌套对象在spring 环境中添加该注解同样会触发bean 校验)。
### 对象嵌套校验
@Valid 校验嵌套对象
```java
public class Project {
@NotBlank(message = "Project title must be present")
@Size(min = 3, max = 20, message = "Project title size not valid")
private String title;
@Valid // 校验嵌套的对象
private User owner;
}
public class User {
// 校验规则
@NotBlank(message = "User name must be present")
@Size(min = 3, max = 50, message = "User name size not valid")
private String name;
// 校验规则
@NotBlank(message = "User email must be present")
@Email(message = "User email format is incorrect")
private String email;
}
```
@Valid 校验可迭代对象
```java
// @Valid 定义在容器对象上
@Valid
private List<Task> tasks;
// @Valid (JSR303注解也可以)定义在泛型参数上
private List<@Valid Task> tasks;
private Map<@Valid User, @Valid Task> assignedTasks;
```
### Validator Api 手动校验BEAN
```java
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
AirportDTO dto = new AirportDTO();
dto.setIataCode("PKX");
dto.setThroughput("-1"); // 符合条件
// data.setValue(1234567.789); // 不符合条件整数部分超过6位
// data.setValue(123456.78901); // 不符合条件小数部分超过4位
// data.setValue(-123.45); // 不符合条件小于0
Set<ConstraintViolation<AirportDTO>> validate = validator.validate(dto,Update.class);
for (ConstraintViolation<AirportDTO> violation : validate) {
System.out.println(violation.getMessage());
}
```