美文网首页
Java Bean Validation校验@PathVaria

Java Bean Validation校验@PathVaria

作者: 十毛tenmao | 来源:发表于2019-05-07 23:01 被阅读0次

Java Bean Validation一般都用在Java Bean的校验上,其实也可以用来校验参数@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;
}

相关文章

网友评论

      本文标题:Java Bean Validation校验@PathVaria

      本文链接:https://www.haomeiwen.com/subject/pryuoqtx.html