article/java/Jsr303校验.md
2025-02-13 14:31:40 +08:00

55 lines
2.7 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的实现
```
### 静态工具 手动校验BEAN
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());
}
}