How do I use @Valid with Spring MVC's @RequestBody parameters?

Hank Gay picture Hank Gay · May 25, 2011 · Viewed 28.3k times · Source

I'm having an issue with using @Valid on a parameter to a handler method on my @Controller. My code looks like this:

@RequestMapping(value=BIBBLE_BOBBLE_URI_PATTERN + "/widgets", method=RequestMethod.POST)
@ResponseBody
@ResponseStatus(HttpStatus.CREATED)
public Widget saveNewWidget(
        @PathVariable final String username,
        @PathVariable final String bibbleBobbleName,
        @Valid @RequestBody final Widget widget,
        final BindingResult results,
        final HttpServletRequest request,
        final HttpServletResponse response)

where Widget is the class for one of my domain objects. I'm using the @RequestBody annotation to indicate that the payload of the request maps to widget (in my tests, the requests are JSON, though Jackson is on my classpath so I could also use XML).

As you can see, the BindingResult parameter follows directly after the Widget parameter, but I get the following error:

java.lang.IllegalStateException: Errors/BindingResult argument declared without preceding model attribute. Check your handler method signature!

How do I apply the @Valid annotation to a @RequestBody parameter and then get the results?

P.S. I'm using annotation-driven to handle wiring up the controllers, do content-negotiation, etc.

Answer

Ritesh picture Ritesh · Jun 13, 2011

Are you using Spring 3.1? It is a newly added feature in Spring version 3.1. Please see Validation For @RequestBody Method Arguments