问题
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:
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 } }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