【问题标题】:@Size not working in SpringBoot Controller@Size 在 SpringBoot 控制器中不起作用
【发布时间】:2018-03-02 19:08:45
【问题描述】:
我正在尝试验证在我的休息端点中传递的列表的大小。
@PostMapping("/test")
public ResponseEntity<String> test(@RequestBody @Size(min = 2) List<Document> docs){
return new ResponseEntity<>(
"Tested",
HttpStatus.OK
);
}
看起来它不起作用。无论我在端点发送多少文件,我都会得到 200 OK。
有没有人知道如何让它工作?
【问题讨论】:
标签:
java
validation
spring-boot
【解决方案1】:
尽量不要使用这样的请求体。最好制作一个以列表作为实例变量的 pojo 或 DTO,并使用 @Valid 注释和 bindingResult 来验证任何实体。
这种方法不可扩展。
【解决方案2】:
它需要 PUT,因为您正在更新资源
@PutMapping("/test")
public ResponseEntity<String> update(@Validated @RequestBody @Size(min = 2) List<Document> docs) {
return new ResponseEntity<>(
"Tested",
HttpStatus.OK
);
}
或者
public class DocumentRequestDto {
@Valid
@Size(min = 2)
private List<Document> documents;
public List<Document> getDocuments() {
return documents;
}
public void setDocuments(List<Document> documents) {
this.documents = documents;
}
}
和控制器
@PutMapping("/test")
public ResponseEntity<String> update(@RequestBody DocumentRequestDto requestDto) {
return new ResponseEntity<>(
"Tested",
HttpStatus.OK
);
}