@Valid working with @ModelAttribute, not with @RequestAttribute

你。 提交于 2020-04-30 06:39:06

问题


I'm implementing a @RestController and I realized that @Valid is working with @RequestBody or @ModelAttribute params of a @GetMapping method, but not with a @RequestAttribute parameter.

To get validated the @RequestAttribute annotated param I have to annotate my Controller class with @Validated.

Following my code:

  1. Controller

    @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 to validate

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

The result is anyCode is not checked to be not null nor empty. If I annotate MyController with @Validate, the ObjectToValidate param is validate as expected. If I change controller as follows, the validation also works.

    @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
        }
   }

Please, could you explain why?


回答1:


@Valid can be used on @RequestBody Controller Method Arguments. That is @RequestBody method argument can be annotated with @Valid to invoke automatic validation.

It will be no use if you annotate ObjectToValidate class with @Valid.

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

To validate the path variable, the controller class should be annotated with @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));
    }

}

Hope it helps!!



来源:https://stackoverflow.com/questions/61333008/valid-working-with-modelattribute-not-with-requestattribute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!