I have the following controller method:
@RequestMapping(value=\"/map/update\", method=RequestMethod.POST, produces = \"application/json; charset=utf-8\")
@Re
Here's my attempt to reconcile the many different answers.
Lebecca's answer works without the need for a wrapper, as Paul's answer requires, because @Validated placed on the class enables the method validation feature of the Bean Validation API.
The Hibernate Validator documentation specifically explains:
[...] the @Valid annotation can be used to mark executable parameters and return values for cascaded validation.
[...]
Cascaded validation can not only be applied to simple object references but also to collection-typed parameters and return values. This means when putting the @Valid annotation to a parameter or return value which
is an array
implements java.lang.Iterable
or implements java.util.Map
each contained element gets validated.
If you need to validate a collection of Beans, this is the most convenient way (make sure to also implement an @ExceptionHandler as required).
If you need to validate a collection of Non-Beans, e.g. a List where each element must match a pattern, you can use container element constraints like this:
controllerMethod(List<@Pattern(regexp="pattern") String> strings)
There's also the possibility to only use @Valid on a controller method parameter (which must then be a Bean type) without also placing @Validated on the class. In that case, you get an appropriate, detailed HTTP 400 response "for free", i.e. without the need for a custom @ExceptionHandler. But this doesn't apply the cascading validation, so you cannot validate something like @Valid List, nor does it support container element constraints.
And finally, you can combine the latter approach with an extra parameter added to the method of type BindingResult. This won't trigger an automatic error response in the case of a validation error, but instead you must inspect the injected BindingResult yourself in the method body and act accordingly (which allows for more flexibility). That is described in this comprehensive answer.