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

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

    Try direct validation. Something like this:

    @Autowired
    Validator validator;
    
    @RequestMapping(method = RequestMethod.POST, value = { "/doesntmatter" })
    @ResponseBody
    public Object myMethod(@RequestBody List 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())
            ...
    
        

    提交回复
    热议问题