JSR提供的校验注解:
javax.validation.constraints
注解 | 校验内容 |
@Null | 为 null |
@NotNull | 不为 null,可以为空字符串 |
@AssertTrue | 为 true |
@AssertFalse | 为 false |
@Min(value) | 数字,最小值 value |
@Max(value) | 数字,最大值 value |
@DecimalMin(value) | 数字,最小值 value |
@DecimalMax(value) | 数字,最大值 value |
@Size (max=, min=) | 集合,长度范围 min ~ max |
@Digits(integer, fraction) | 数字,在 integer 上下浮动不超过 fraction |
@Past | 过去的日期 |
@Futrue | 将来的日期 |
@Pattern(regex=, flag=) | 符合正则表达式 |
Hibernate Validator 提供的校验注解:
org.hibernate.validator.constraints
@NotBlank(message=) | 字符串,非 null,且 trim() 后长度大于0 |
@NotEmpty | 集合,非空 |
电子邮箱地址 | |
@Length(min=, max=) | 字符串,长度范围 min ~ max |
@Range(min=, max=, message=) | 指定范围 min ~ max |
开启校验方式
一(常用):
@Validated @RequestBody SaleInvoiceDetailQuery query
二:建立utils使用
private static ValidatorFactory factory;
private static Validator validator;
static {
factory = Validation.buildDefaultValidatorFactory();
validator = factory.getValidator();
}
validator.validate(需要校验的对象);