@Valid注解相关
-
依赖
-
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-validation</artifactId> </dependency> <!--或者 ------- --> <dependency> <groupId>javax.validation</groupId> <artifactId>validation-api</artifactId> <version>1.1.0.Final</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>5.4.1.Final</version> </dependency>
验证注解 | 验证的数据类型 | 说明 |
---|---|---|
@Valid | 任何非原子类型 | 指定递归验证关联的对象如用户对象中有个地址对象属性,如果想在验证用户对象时一起验证地址对象的话,在地址对象上加@Valid注解即可级联验证 |
@AssertFalse | Boolean,boolean | 验证注解的元素值是false |
@AssertTrue | Boolean,boolean | 验证注解的元素值是true |
@Null | 任意类型 | 验证注解的元素值是null |
@NotNull | 任意类型 | 验证注解的元素值不是null |
@NotEmpty | CharSequence子类型、Collection、Map、数组 | 验证注解的元素值不为null且不为空(字符串长度不为0、集合大小不为0) |
@NotBlank | CharSequence子类型 | 验证注解的元素值不为空(不为null、去除首位空格后长度为0),不同于@NotEmpty,@NotBlank只应用于字符串且在比较时会去除字符串的首位空格 |
@Length(min=下限, max=上限) | CharSequence子类型 | 验证注解的元素值长度在min和max区间内 |
@Size(min=下限, max=上限) | 字符串、Collection、Map、数组等 | 验证注解的元素值的在min和max(包含)指定区间之内,如字符长度、集合大小 |
@Range(min=最小值, max=最大值) | BigDecimal,BigInteger,CharSequence, byte, short, int, long等原子类型和包装类型 | 验证注解的元素值在最小值和最大值之间 |
@Min(value=值) | BigDecimal,BigInteger, byte,short, int, long,等任何Number或CharSequence(存储的是数字)子类型 | 验证注解的元素值大于等于@Min指定的value值 |
@Max(value=值) | 和@Min要求一样 | 验证注解的元素值小于等于@Max指定的value值 |
@DecimalMin(value=值) | 和@Min要求一样 | 验证注解的元素值大于等于@ DecimalMin指定的value值 |
@DecimalMax(value=值) | 和@Min要求一样 | 验证注解的元素值小于等于@ DecimalMax指定的value值 |
@Digits(integer=整数位数, fraction=小数位数) | 和@Min要求一样 | 验证注解的元素值的整数位数和小数位数上限 |
@Past | java.util.Date,java.util.Calendar;Joda Time类库的日期类型 | 验证注解的元素值(日期类型)比当前时间早 |
@PastOrPresent | 与@Past要求一样 | 验证注解的元素值(日期类型)是当前时间或者比当前时间早 |
@Future | 与@Past要求一样 | 验证注解的元素值(日期类型)比当前时间晚 |
@FutureOrPresent | 与@Past要求一样 | 验证注解的元素值(日期类型)是当前时间或者比当前时间晚 |
@Email(regexp=正则表达式,flag=标志的模式) | CharSequence子类型(如String) | 验证注解的元素值是Email,也可以通过regexp和flag指定自定义的email格式 |
@Pattern(regexp=正则表达式,flag=标志的模式) | String,任何CharSequence的子类型 | 验证注解的元素值与指定的正则表达式匹配 |
@NouNull、@NotEmpty、@NotBlank
@NotEmpty注解的String、Collection、Map、数组不能为null或者长度为0的(纯空格的String符合规则)
@NotBlank注释的String不能为null或空的 (尾部空格被忽略,纯空格的String也是不符合规则。即trim()之后,要length>0才符合)
@NotNull 注释的元素不能为null,但可以为empty,没有长度的约束。接受任何类型
String str = null; //都不能为null
@NotNull: false
@NotEmpty: false
@NotBlank: false
String str = "";
@NotNull: true //可以为空 没有长度限制
@NotEmpty: false
@NotBlank: false
String str = " ";
@NotNull: true
@NotEmpty: true //长度为1 不除去空格
@NotBlank: false //用trim()后 长度为0
String str = "Hello!";
@NotNull: true
@NotEmpty: true
@NotBlank: true
使用案例
@RequestMapping("/test")
@RestController
// 和get请求一起使用
@Validated
public class DemoController {
@RequestMapping("test2")
public String test2(@Valid @RequestBody Test2DTO param) {
System.out.println(param);
return "success";
}
@RequestMapping("test3")
public Integer test3(@RequestParam @Min(value = 1L) Integer id) {
return id;
}
@RequestMapping("test4/{id}")
public Integer test4(@PathVariable("id") @Min(value = 1L) Integer id){
return id;
}
}
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Test2DTO {
@NotNull
@Min(value = 1L,message = "Error_id")
private Integer id;
@NotNull
@Length(max = 5,message = "ErrorUsername")
private String username;
}
// 对于格式校验抛出的异常做处理(无需求可以不使用)
@RestControllerAdvice
public class ValidExceptionAdvice {
private Resp<?> response(int errorCode, Exception e) {
return new Resp<>(errorCode, e.getClass().getSimpleName() + "/" + e.getMessage());
}
/**
* 处理@PathVariable和@RequestParam使用注解抛出的异常
*/
@ExceptionHandler(value = {ValidationException.class})
@ResponseStatus(HttpStatus.BAD_REQUEST)
public Resp<?> validationException(Exception e) {
return response(1, e);
}
/**
* 处理 @RequestBody 格式校验的异常
*/
@ExceptionHandler(value = {MethodArgumentNotValidException.class})
@ResponseStatus(HttpStatus.PRECONDITION_FAILED)
public Resp<?> methodArgumentNotValidException(MethodArgumentNotValidException e) {
String message = e.getBindingResult().getAllErrors().stream()
.map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.joining(";"));
return new Resp<>(3, message);
}
}
@Data
public class Resp<T> {
public static final Resp<Void> VOID = new Resp();
public int code = 0;
public String message;
public T data;
public Resp() {
}
public Resp(int code, String message) {
this.code = code;
this.message = message;
}
public Resp(T data) {
this.data = data;
}
}