validation-api参数校验
这里针对springboot项目结构
maven添加:
<dependency> <groupId>javax.validation</groupId> <artifactId>validation-api</artifactId> </dependency>
controller(@Validated、@Valid)
@PostMapping("/test.do") public JSONMessageResponse test(@Validated @RequestBody TestVO testVO) { }
TestVO
public class TestVO { @NotEmpty(message = "名称不能为空") String name; // 名称 @ListNotEmptyNull(message = "不能为空的数组") // 自定义 @ListSize(min = 1, max = 5, message = "错误的数组大小") @Valid List<UserVO> list; }
public class UserVO { @NotEmpty(message = "名称不能为空") String name; // 名称 }
错误拦截
@ControllerAdvice public class GlobalExceptionHandler extends ResponseEntityExceptionHandler { @Override protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest request) { BindingResult bindingResult = ex.getBindingResult(); String errorMessage = "参数校验失败"; for (FieldError fieldError : bindingResult.getFieldErrors()) { errorMessage += ", " + fieldError.getDefaultMessage(); } JSONMessageResponse error = SystemResultUtil.error(5006, errorMessage); return new ResponseEntity<>(error, HttpStatus.BAD_REQUEST); } }
查看返回(返回结构可自定义,这里不详细指出)
{ "code": 5006, "message": "参数校验失败,名称不能为空",
"status": 1
}
对于列表的操作,可以自定义:例如下面的指定list的大小(当然,自带的@Size可以实现)
/** * 指定列表的大小 * * @author sky.javaweb@qq.com * @version 1.0 * @date 2019-01-07 */ @Target({ANNOTATION_TYPE, METHOD, FIELD}) @Retention(RUNTIME) @Documented @Constraint(validatedBy = ListSizeValidationImpl.class)////此处指定了注解的实现类为ListSizeValidationImpl public @interface ListSize { int min() default 0; int max() default Integer.MAX_VALUE; String message() default "List集合大小错误"; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; /** * 定义List,为了让Bean的一个属性上可以添加多套规则 */ @Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER}) @Retention(RUNTIME) @Documented @interface List { ListSize[] value(); } }
/** * @author sky.javaweb@qq.com * @version 1.0 * @date 2019-01-07 */ @Service public class ListSizeValidationImpl implements ConstraintValidator<ListSize, List> { private int min; private int max; @Override public void initialize(ListSize constraintAnnotation) { this.min = constraintAnnotation.min(); this.max = constraintAnnotation.max(); } @Override public boolean isValid(List list, ConstraintValidatorContext context) { if (list != null) { if (list.size() < min || list.size() > max) { return false; } } return true; } }
使用如下:
@ListSize(min = 2, max = 5, message = "无效的案例图片") List<String> imageList; // 图片
{ "code": 5006, "message": "参数校验失败, 无效的案例图片", "status": 1 }