@Size在Spring Boot Controller中不起作用

问题描述 投票:0回答:2

我试图验证在我的休息端点传递的列表的大小。

@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
2个回答
0
投票

尽量不要使用像这样的请求体...更好地使用列表作为其实例变量的pojo或DTO,并使用@Valid annotation和bindingResult来验证任何实体。这种方法不可扩展。


0
投票

它需要是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
    );
}
© www.soinside.com 2019 - 2024. All rights reserved.