本文内容摘要:
springboot 注解参数校验,controller 层参数校验 (单个参数接收,实体参数接收,post,get方法请求的参数校验),全局参数异常处理
springboot中的几种参数校验方式。常用的用于参数校验的注解如下:
@AssertFalse 所注解的元素必须是Boolean类型,且值为false
@AssertTrue 所注解的元素必须是Boolean类型,且值为true
@DecimalMax 所注解的元素必须是数字,且值小于等于给定的值
@DecimalMin 所注解的元素必须是数字,且值大于等于给定的值
@Digits 所注解的元素必须是数字,且值必须是指定的位数
@Future 所注解的元素必须是将来某个日期
@Max 所注解的元素必须是数字,且值小于等于给定的值
@Min 所注解的元素必须是数字,且值小于等于给定的值
@Range 所注解的元素需在指定范围区间内
@NotNull 所注解的元素值不能为null
@NotBlank 所注解的元素值有内容
@Null 所注解的元素值为null
@Past 所注解的元素必须是某个过去的日期
@PastOrPresent 所注解的元素必须是过去某个或现在日期
@Pattern 所注解的元素必须满足给定的正则表达式
@Size 所注解的元素必须是String、集合或数组,且长度大小需保证在给定范围之内
@Email 所注解的元素需满足Email格式
controller 层参数校验分2种
一,单个参数校验:
在controller类上加上 @Validated
如图:
接口参数:加上注解
如图:
校验参数抛出异常:ConstraintViolationException 最后全局参数处理
二,实体类参数校验:
实体字段上添加注解:
get请求:
参数注解:
校验参数抛出异常:BindException 最后全局参数处理
post请求:
参数注解:
校验参数抛出异常:MethodArgumentNotValidException 最后全局参数处理
参数全局校验:
全局异常处理源码:
/**
* 实体接收参数校验 post MethodArgumentNotValidException,get BindException
* 单个接收参数 ConstraintViolationException
* @param e
* @return
*/
@ExceptionHandler(value = {MethodArgumentNotValidException.class, BindException.class, ConstraintViolationException.class})
@ResponseBody
public Result handleValidException(Exception e) {
if (e instanceof MethodArgumentNotValidException) {
MethodArgumentNotValidException me = (MethodArgumentNotValidException) e;
return wrapperBindingResult(me.getBindingResult());
}
if (e instanceof BindException) {
BindException be = (BindException) e;
return wrapperBindingResult(be.getBindingResult());
}
if (e instanceof ConstraintViolationException) {
return wrapperConstraintViolationExceptionResult((ConstraintViolationException) e);
}
return new Result("400", "参数错误");
}
private Result wrapperConstraintViolationExceptionResult(ConstraintViolationException e) {
StringBuilder msg = new StringBuilder();
Set<ConstraintViolation<?>> constraintViolations = e.getConstraintViolations();
if (CollectionUtils.isEmpty(constraintViolations)) {
return new Result("400", "参数错误");
}
for (ConstraintViolation<?> item : constraintViolations) {
String propertyPath = item.getPropertyPath().toString();
msg.append(", ").append(propertyPath.split("\\.")[1]).append(": ").append(item.getMessage());
}
return new Result("400", msg.substring(2));
}
private Result wrapperBindingResult(BindingResult bindingResult) {
StringBuilder msg = new StringBuilder();
List<ObjectError> allErrors = bindingResult.getAllErrors();
if (CollectionUtils.isEmpty(allErrors)) {
return new Result("400", "参数错误");
}
for (ObjectError error : allErrors) {
msg.append(", ");
if (error instanceof FieldError) {
msg.append(((FieldError) error).getField()).append(": ");
}
msg.append(error.getDefaultMessage() == null ? "" : error.getDefaultMessage());
}
return new Result("400", msg.substring(2));
}
执行结果:
单个参数:get,post
实体参数:get,post