Java Bean Validation校验@PathVaria
2019-05-07 本文已影响0人
十毛tenmao
Java Bean Validation一般都用在Java Bean的校验上,其实也可以用来校验参数
@PathVariable
和@RequestParam
- Java Bean Validation的初步使用
- Java Bean Validation自定义注解
- Java Bean Validation分组校验
- Java Bean Validation校验@PathVariable和@RequestParam
配置校验规则
//支持@PathVariable
//支持@RequestParam
@PutMapping("update/{uid:\\w+}")
public WebResult<Void> update(@Valid @Length(min = 2, max = 3, message = "uid should between 2 and 3") @PathVariable String uid,
@Valid @Length(min = 4, max = 5, message = "name should between 4 and 5") @RequestParam String name,
@Validated({UpdateGroup.class, Default.class}) @RequestBody Person person) {
log.info("person to update: {}", person);
return WebResult.SUCCESS;
}
添加@Validated
上面配置后,还是不能起作用,还需要在Controller上增加注解@Validated
@Slf4j
@SpringBootApplication
@RestController
@Validated
public class ValidationApplication {
public static void main(String[] args) {
SpringApplication.run(ValidationApplication.class, args);
}
@PutMapping("update/{uid:\\w+}")
public WebResult<Void> update(@Valid @Length(min = 2, max = 3, message = "uid should between 2 and 3") @PathVariable String uid,
@Valid @Length(min = 4, max = 5, message = "name should between 4 and 5") @RequestParam String name,
@Validated({UpdateGroup.class, Default.class}) @RequestBody Person person) {
log.info("person to update: {}", person);
return WebResult.SUCCESS;
}
}
自定义返回值
校验失败后抛出的异常是ConstraintViolationException
,不是MethodArgumentNotValidException
,所以也需要额外进行处理
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(MethodArgumentNotValidException.class)
public <T> WebResult<T> handleValidationExceptions(
MethodArgumentNotValidException ex) {
WebResult<T> result = new WebResult<>();
result.setCode(400);
String errorMsg = ex.getBindingResult().getAllErrors().stream()
.map(DefaultMessageSourceResolvable::getDefaultMessage)
.collect(Collectors.joining("\n", "[", "]"));
result.setMsg(errorMsg);
return result;
}
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(ConstraintViolationException.class)
public <T> WebResult<T> handleConstraintViolationException(
ConstraintViolationException ex) {
WebResult<T> result = new WebResult<>();
result.setCode(400);
String errorMsg = ex.getConstraintViolations().stream()
.map(ConstraintViolation::getMessage)
.collect(Collectors.joining("\n", "[", "]"));
result.setMsg(errorMsg);
return result;
}