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

后端 未结 10 2155
醉酒成梦
醉酒成梦 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:30

    There is a elegant way to wrapper your request in a custom java.util.List which acts as both List and JavaBean. see here

    0 讨论(0)
  • 2020-11-29 23:31

    Try direct validation. Something like this:

    @Autowired
    Validator validator;
    
    @RequestMapping(method = RequestMethod.POST, value = { "/doesntmatter" })
    @ResponseBody
    public Object myMethod(@RequestBody List<Object> request, BindingResult bindingResult) {
        for (int i = 0; i < request.size(); i++) {
            Object o = request.get(i);
            BeanPropertyBindingResult errors = new BeanPropertyBindingResult(o, String.format("o[%d]", i));
            validator.validate(o, errors);
            if (errors.hasErrors())
                bindingResult.addAllErrors(errors);
        }
        if (bindingResult.hasErrors())
            ...
    
    0 讨论(0)
  • 2020-11-29 23:32

    Implement your own validator with org.springframework.validation.beanvalidation.LocalValidatorFactoryBean as a member and call that validator for each item.

    public class CheckOutValidator implements Validator {
    
    
        private Validator validator;
    
       @Override
        public void validate(Object target, Errors errors) { 
        List request = (List) target;
        Iterator it = request.iterator()   
        while(it.hasNext()) {
        MyBean b = it.next();
        validator.validate(b, errors);
    
         }
    
         }
    
    //setters and getters
    
    }
    
    0 讨论(0)
  • 2020-11-29 23:33

    Using com.google.common.collect.ForwardingList

    public class ValidList<T> extends ForwardingList<T> {
    
      private List<@Valid T> list;
    
      public ValidList() {
        this(new ArrayList<>());
      }
    
      public ValidList(List<@Valid T> list) {
        this.list = list;
      }
    
      @Override
      protected List<T> delegate() {
        return list;
      }
    
      /** Exposed for the {@link javax.validation.Validator} to access the list path */
      public List<T> getList() {
        return list;
      }
    }
    

    So no need for the wrapper

    you may use

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

    By using wrapper your JSON needs to be changed to

    {
      "list": []
    }
    

    with this implementation you can use original JSON

    []
    
    0 讨论(0)
  • 2020-11-29 23:34

    @Valid is a JSR-303 annotation and JSR-303 applies to validation on JavaBeans. A java.util.List is not a JavaBean (according to the official description of a JavaBean), hence it cannot be validated directly using a JSR-303 compliant validator. This is supported by two observations.

    Section 3.1.3 of the JSR-303 Specification says that:

    In addition to supporting instance validation, validation of graphs of object is also supported. The result of a graph validation is returned as a unified set of constraint violations. Consider the situation where bean X contains a field of type Y. By annotating field Y with the @Valid annotation, the Validator will validate Y (and its properties) when X is validated. The exact type Z of the value contained in the field declared of type Y (subclass, implementation) is determined at runtime. The constraint definitions of Z are used. This ensures proper polymorphic behavior for associations marked @Valid.

    Collection-valued, array-valued and generally Iterable fields and properties may also be decorated with the @Valid annotation. This causes the contents of the iterator to be validated. Any object implementing java.lang.Iterable is supported.

    I have marked the important pieces of information in bold. This section implies that in order for a collection type to be validated, it must be encapsulated inside a bean (implied by Consider the situation where bean X contains a field of type Y); and further that collections cannot be validated directly (implied by Collection-valued, array-valued and generally Iterable fields and properties may also be decorated, with emphasis on fields and properties).

    Actual JSR-303 implementations

    I have a sample application that tests collection validation with both Hibernate Validator and Apache Beans Validator. If you run tests on this sample as mvn clean test -Phibernate (with Hibernate Validator) and mvn clean test -Papache (for Beans Validator), both refuse to validate collections directly, which seems to be in line with the specification. Since Hibernate Validator is the reference implementation for JSR-303, this sample is further proof that collections need to be encapsulated in a bean in order to be validated.


    With that cleared, I would say that there is also a design problem in trying to pass a collection to a controller method directly in the way shown in the question. Even if validations were to work on the collections directly, the controller method will be unable to work with alternate data representations such as custom XML, SOAP, ATOM, EDI, Google Protocol Buffers etc. which do not map directly to collections. For supporting those representations, the controller must accept and return object instances. That would require encapsulating the collection inside an object instance any way. It would therefore be highly advisable to wrap the List inside another object as other answers have suggested.

    0 讨论(0)
  • 2020-11-29 23:37

    If you don't want to write a wrapper for each List you have, you can use a generic wrapper:

    public class ListWrapper<E> {
    
        private List<E> list;
    
        public ListWrapper() {
            list = new ArrayList<>();
        }
    
        public ListWrapper(List<E> list) {
            this.list = list;
        }
    
        @Valid
        public List<E> getList() {
            return list;
        }
    
        public void setList(List<E> list) {
            this.list = list;
        }
    
        public boolean add(E e) {
            return list.add(e);
        }
    
        public void clear() {
            list.clear();
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题