前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Java Bean Validation校验@PathVariable和@RequestParam

Java Bean Validation校验@PathVariable和@RequestParam

作者头像
十毛
发布2019-05-15 14:42:56
2.9K0
发布2019-05-15 14:42:56
举报
文章被收录于专栏:用户1337634的专栏

Java Bean Validation一般都用在Java Bean的校验上,其实也可以用来校验参数@PathVariable和@RequestParam

配置校验规则

代码语言:javascript
复制
//支持@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

代码语言:javascript
复制
@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,所以也需要额外进行处理

代码语言:javascript
复制
@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;
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019.05.07 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 配置校验规则
  • 添加@Validated
  • 自定义返回值
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档