【问题标题】:@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。

有没有人知道如何让它工作?

【问题讨论】:

  • GET 请求不可能有请求正文。
  • 改成@PutMapping

标签: 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
        );
    }
    

    【讨论】:

    猜你喜欢
    • 2020-06-26
    • 2020-11-06
    • 2015-05-26
    • 1970-01-01
    • 2021-04-30
    • 1970-01-01
    • 2016-03-11
    • 2013-04-30
    • 2019-06-28
    相关资源
    最近更新 更多