Spring MVC - @Valid on list of beans in REST service

后端 未结 10 2189
醉酒成梦
醉酒成梦 2020-11-29 23:05

In a Spring MVC REST service (json), I have a controller method like this one :

@RequestMapping(method = RequestMethod.POST, value = { \"/doesntmatter\" })
         


        
10条回答
  •  一向
    一向 (楼主)
    2020-11-29 23:43

    The only way i could find to do this is to wrap the list, this also means that the JSON input would have to change.

    @RequestMapping(method = RequestMethod.POST, value = { "/doesntmatter" })
    @ResponseBody
    public List<...> myMethod(@Valid @RequestBody List request, BindingResult bindingResult) {
    

    becomes:

    @RequestMapping(method = RequestMethod.POST, value = { "/doesntmatter" })
    @ResponseBody
    public List<...> myMethod(@Valid @RequestBody MyBeanList request, BindingResult bindingResult) {
    

    and we also need:

    import javax.validation.Valid;
    import java.util.List;
    
    public class MyBeanList {
    
        @Valid
        List list;
    
        //getters and setters....
    }
    

    This looks like it could also be possible with a custom validatior for lists but i have not got that far yet.

    The @Valid annotation is part of the standard JSR-303 Bean Validation API, and is not a Spring-specific construct. Spring MVC will validate a @Valid object after binding so-long as an appropriate Validator has been configured.

    Reference : http://docs.spring.io/spring/docs/current/spring-framework-reference/html/validation.html

提交回复
热议问题