本文主要针对controller层中,对于单个参数的校验:
1、引入依赖
org.hibernate hibernate-validator 5.3.1.Final 2、首先,需要我们声明一个Bean,注入校验器到Spring Boot的运行环境,负责不能生效对应的@Range、@Min、@Max等validator包里面提供的注解@Configuration
@EnableAutoConfiguration
public class ValidatorConfig {
@Bean
public MethodValidationPostProcessor methodValidationPostProcessor(){
return new MethodValidationPostProcessor();
}
}
3、controller层
特别注意:
1、@Validated要在controller上标注
@Api(value = “type”, description = “辅导类型”)
@RestController
@Validated
@RequestMapping(value = “type”)
public class CompositionTypesController extends BaseController {
@ApiOperation(value=“新增辅导类型”, notes=“新增辅导类型”)
@LoginRequired
@PostMapping(value = “addCompostionTyp1e”)
public Response addCompostionTyp1e(@ApiParam(value = “成绩”) @Max(value = 60,message = “得分必须小于60”) @RequestParam int score, @ApiParam(value = “年龄”) @Min(value = 3, message = “年龄大于3岁”) @RequestParam int age, @ApiParam(value = “辅导作文类型”) @NotNull(message = “辅导作文类型不能为空”) @RequestParam(required = false) String name){
//校验
logger.info(String.valueOf(age));
return success(ResponseCode.OK);
}
}
4、统一异常捕获
@ControllerAdvice
public class ExceptionAdvice {
/**
* 拦截捕捉自定义异常 ConstraintViolationException.class
* @param ex
* @return
*/
@ResponseBody
@ExceptionHandler(value = ConstraintViolationException.class)
public Map ConstraintViolationExceptionHandler(ConstraintViolationException ex) {
Map map = new HashMap();
Set<ConstraintViolation<?>> constraintViolations = ex.getConstraintViolations();
Iterator<ConstraintViolation<?>> iterator = constraintViolations.iterator();
List msgList = new ArrayList<>();
while (iterator.hasNext()) {
ConstraintViolation<?> cvl = iterator.next();
msgList.add(cvl.getMessageTemplate());
}
map.put(“status”, ExceptionCode.CVL_EXCEPTION);
map.put(“msg”, msgList);
return map;
}
}
5、在swagger中进行接口调试
注:
校验常用的注解如下:
@AssertFalse 校验false
@AssertTrue 校验true
@DecimalMax(value=,inclusive=) 小于等于value,
inclusive=true,是小于等于
@DecimalMin(value=,inclusive=) 与上类似
@Max(value=) 小于等于value
@Min(value=) 大于等于value
@NotNull 检查Null
@Past 检查日期
@Pattern(regex=,flag=) 正则
@Size(min=, max=) 字符串,集合,map限制大小
@Valid 对po实体类进行校验
@NotNull 和 @NotEmpty 和@NotBlank 区别
@NotEmpty 用在集合类上面
@NotBlank 用在String上面
@NotNull 用在基本类型上