javax.validation.Valid;
1、使用
在Controller上使用@Valid注解
public String payment(@RequestBody @Valid PrivatePayReq req){};
二级嵌套对象校验不作用问题
在二级对象上使用@Valid注解
public class PrivatePayReq{
@Valid
@NotNull(message="退费对象不可为空")
private PrivateRefundReq refundReq;
}
2、异常处理 MethodArgumentNotValidException
// 基于Handle或Filter
if (e instanceof MethodArgumentNotValidException) {
String errorMsg = ((MethodArgumentNotValidException) e).getBindingResult().getAllErrors().stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.joining(","));
resp = R.builder().code(ResultCodeEnum.BUSINESS_ERROR.getCode()).message(errorMsg).success(false).build();
}
// 基于异常监听@ControllerAdvice
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseBody
public R customException(MethodArgumentNotValidException e) {
e.printStackTrace();
String errorMsg = e.getBindingResult().getAllErrors().stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.joining(","));
return R.builder().code(ResultCodeEnum.BUSINESS_ERROR.getCode()).message(errorMsg).success(false).build();
}
3、常用注解的使用
@Valid
声明使用javax.validation.Valid校验,一般作用于Controller方法对象校验,或嵌套二级对象校验。
@Null 对象,为空 Bean Validation 1.0
@NotNull 对象,不为空 Bean Validation 1.0
@AssertTrue 布尔,为True Bean Validation 1.0
@AssertFalse 布尔,为False Bean Validation 1.0
@Min(value) 数字,最小为value Bean Validation 1.0
@Max(value) 数字,最大为value Bean Validation 1.0
@DecimalMin(value) 数字,最小为value Bean Validation 1.0
@DecimalMax(value) 数字,最大为value Bean Validation 1.0
@Size(max, min) min<=value<=max Bean Validation 1.0
@Digits (integer, fraction) 数字,某个范围内 Bean Validation 1.0
@Past 日期,过去的日期 Bean Validation 1.0
@Future 日期,将来的日期 Bean Validation 1.0
@Pattern(value) 字符串,正则校验 Bean Validation 1.0
@Email 字符串,邮箱类型 Bean Validation 2.0
@NotEmpty 集合,不为空 Bean Validation 2.0
@NotBlank 字符串,不为空字符串 Bean Validation 2.0
@Positive 数字,正数 Bean Validation 2.0
@PositiveOrZero 数字,正数或0 Bean Validation 2.0
@Negative 数字,负数 Bean Validation 2.0
@NegativeOrZero 数字,负数或0 Bean Validation 2.0
@PastOrPresent 过去或者现在 Bean Validation 2.0
@FutureOrPresent 将来或者现在 Bean Validation 2.0