zoukankan      html  css  js  c++  java
  • @RequestBody与@Validated一起使用校验失效

    请求参数多层嵌套时与注解@RequestBody一起使用时就会产生 校验失效问题

     1. 请看代码

     @PostMapping("/addRole")
        public ResponseData<Boolean> addRole(@RequestBody @Validated RoleListParam roleParam) {
            return ResponseData.success(dramaService.addRole(roleParam));
        }

     2.参数嵌套

    @ApiModel(value = "描述信息")
    @Data
    @Accessors(chain = true)
    public class RoleListParam {
     
        @ApiModelProperty("id")
        @NotNull(message = "id不能为空")
        private Long id;
     
        @ApiModelProperty("参数")
        private List<RoleParam> roleParamList;
     
        @ApiModelProperty("参数集合")
        private List<DramaDmParam> dmParams;
     
    }

    3.深一层就不写了

    4.上述写法 校验不会生效

    解决校验问题

    5.

            1.看代码

     @ApiOperation("描述信息")
        @PostMapping("/addRole")
        public ResponseData<Boolean> addRole(@RequestBody @Valid RoleListParam roleParam) {
            return ResponseData.success(dramaService.addRole(roleParam));
        }

            2.嵌套数据中

     
        @ApiModelProperty("id")
        @NotNull(message = "id不能为空")
        private Long dramaId;
     
     
        @ApiModelProperty("参数")
        @Valid
        private List<RoleParam> roleParamList;
     
        @ApiModelProperty("参数集合")
        @Valid
        private List<DramaDmParam> dmParams;

            3.这样写校验生效了需要我们在异常以拦截器中写自定义拦截类

    @ExceptionHandler(MethodArgumentNotValidException.class)
        public ResponseData<Object> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
            StringBuilder msg = new StringBuilder();
            List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
            for (ObjectError allError : allErrors) {
                msg.append(allError.getDefaultMessage());
            }
            return ResponseData.fail(ResponseCode.PARAM_INVALIDATE.getCode(), msg.toString());
        }

    注意:

    BindException是@Validation单独使用校验失败时产生的异常
    MethodArgumentNotValidException是@RequestBody和@Validated配合时产生的异常,比如在传参时如果前端的json数据里部分缺失@RequestBody修饰的实体类的属性就会产生这个异常。


  • 相关阅读:
    一键编译go文件命令.bat
    安装go语言,配置环境及IDE,只需3步
    Mysql show Status常用参数详解
    LFS:kernel panic VFS: Unable to mount root fs
    LFS: Interface eth0 doesn't exist
    转:Xshell显示找不到匹配的outgoing encryption算法怎么办
    NTP-ntpdate:no server suitable for synchronization found
    linux/module.h: No such file or directory 内核模块编译过程
    ASCII码表完整版
    [Firmware Warn]: GHES: Failed to read error status block address for hardware error source
  • 原文地址:https://www.cnblogs.com/shisanye/p/15162021.html
Copyright © 2011-2022 走看看