@Valid 与 @ModelAttribute 一起工作,而不是与 @RequestAttribute 一起工作 [英] @Valid working with @ModelAttribute, not with @RequestAttribute
问题描述
我正在实现一个 @RestController
并且我意识到 @Valid
正在使用 @RequestBody
或 @ModelAttribute
@GetMapping
方法的参数,但不包含 @RequestAttribute
参数.
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.
要验证 @RequestAttribute
注释参数,我必须使用 @Validated
注释我的 Controller 类.
To get validated the @RequestAttribute
annotated param I have to annotate my Controller class with @Validated
.
遵循我的代码:
控制器
@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
Bean to validate
@Getter
@Setter
@Valid
public class ObjectToValidate {
@NotNull
@NotEmpty
private String anyCode;
}
结果是 anyCode 没有被检查为非 null 或空.如果我用 @Validate
注释 MyController,ObjectToValidate
参数会按预期验证.如果我按如下方式更改控制器,则验证也有效.
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
}
}
请你解释一下为什么?
推荐答案
@Valid 可用于@RequestBody 控制器方法参数.即@RequestBody 方法参数可以使用@Valid 进行注释以调用自动验证.
@Valid can be used on @RequestBody Controller Method Arguments. That is @RequestBody method argument can be annotated with @Valid to invoke automatic validation.
如果用@Valid 注释 ObjectToValidate 类将没有用.
It will be no use if you annotate ObjectToValidate class with @Valid.
@PostMapping("/notes")
Note getNote(@Valid @RequestBody Note note) {
return repository.save(note);
}
要验证路径变量,控制器类应该用@Validated进行注释
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));
}
}
希望能帮到你!!
这篇关于@Valid 与 @ModelAttribute 一起工作,而不是与 @RequestAttribute 一起工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!