简体   繁体   中英

@Size not working in SpringBoot Controller

I am trying to validate the size of the list passed in my rest endpoint.

@PostMapping("/test")
public ResponseEntity<String> test(@RequestBody @Size(min = 2) List<Document> docs){
        return new ResponseEntity<>(
                "Tested",
                HttpStatus.OK
        );
    }

Looks like it's not working. I am getting 200 OK regardless of the number of documents i send in the endpoint.

Does anybody knows any way to get it working?

It needs to be PUT since you are updating a resource

@PutMapping("/test")
public ResponseEntity<String> update(@Validated @RequestBody @Size(min = 2) List<Document> docs) {
    return new ResponseEntity<>(
            "Tested",
            HttpStatus.OK
    );
}

Or

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;
    }
}

And controller

@PutMapping("/test")
public ResponseEntity<String> update(@RequestBody DocumentRequestDto requestDto) {
    return new ResponseEntity<>(
            "Tested",
            HttpStatus.OK
    );
}

Try not to use requests body like this..better make a pojo or DTO having list as its instance variables and use @Valid annotation and bindingResult to validate any entity. This approach is not scalable.

I had the same issue and fixed it by adding @Validated to controller(class) itself

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM