【问题标题】:@Valid working with @ModelAttribute, not with @RequestAttribute@Valid 使用 @ModelAttribute,而不是 @RequestAttribute
【发布时间】:2020-04-20 22:19:28
【问题描述】:

我正在实现 @RestController 并且我意识到 @Valid 正在使用 @RequestBody 或 @ModelAttribute 参数 @GetMapping 方法,但不是 @RequestAttribute 参数。

要验证 @RequestAttribute 带注释的参数,我必须使用 @Validated 注释我的 Controller 类。

按照我的代码:

  1. 控制器

    @Log4j2
    @RestController
    @RequestMapping("/test/api/v1/entity")
    public class MyController extends SomeController {
    
      @GetMapping("/getInfo")
      public ResponseEntity<<MyResponse>> infoStatus (RequestParam(required = false) String inputStr,
      @Valid @RequestAttribute ObjectToValidate objToValidate){
           //Any stuff here
      }
    }
    
  2. 要验证的 Bean

    @Getter
    @Setter
    @Valid 
    public class ObjectToValidate {
    
      @NotNull
      @NotEmpty
      private String anyCode;
    }
    

结果是 anyCode 未被检查为不为空也不为空。 如果我用 @Validate 注释 MyController,ObjectToValidate 参数将按预期进行验证。 如果我按如下方式更改控制器,则验证也有效。

    @Log4j2
    @RestController
    @RequestMapping("/test/api/v1/entity")
    public class MyController extends SomeController {

        @ModelAttribute 
        public ObjectToValidate addToModel(@RequestAttribute ObjectToValidate
        objToValidate) { return objToValidate; }

        @GetMapping("/getInfo")
        public ResponseEntity<MyResponse> infoStatus (
                @RequestParam(required = false) String inputStr,
                @Valid @ModelAttribute ObjectToValidate objToValidate
        ){
           //Any stuff here
        }
   }

请问,你能解释一下原因吗?

【问题讨论】:

    标签: spring-boot validation spring-mvc


    【解决方案1】:

    @Valid 可用于@RequestBody 控制器方法参数。 即@RequestBody 方法参数可以用@Valid 注释来调用自动验证。

    如果你用 @Valid 注释 ObjectToValidate 类是没有用的。

    @PostMapping("/notes")
    Note getNote(@Valid @RequestBody Note note) {
        return repository.save(note);
    }
    

    要验证路径变量,控制器类应该用@Validated注解

    @RestController
    @Validated // class level
    public class NoteController {
    
        @GetMapping("/note/{id}")
        Note findOne(@PathVariable @NotBlank(message = "Id must not be empty") String id) { 
            return repository.findById(id)
                    .orElseThrow(() -> new NotekNotFoundException(id));
        }
    
    }
    

    希望对你有帮助!!

    【讨论】:

      猜你喜欢
      • 2012-12-03
      • 2014-05-04
      • 1970-01-01
      • 2020-09-15
      • 2012-12-04
      • 2019-05-21
      • 1970-01-01
      • 2013-08-02
      相关资源
      最近更新 更多