如何在Spring MVC的@RequestBody参数中使用@Valid?


问题内容

我在@Valid的处理程序方法的参数上使用参数时遇到问题@Controller。我的代码如下所示:

@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)

Widget我的域对象之一的类在哪里?我正在使用@RequestBody批注指示请求的有效负载映射到widget(在我的测试中,请求是JSON,尽管Jackson在我的类路径中,所以我也可以使用XML)。

如您所见,BindingResult参数紧随Widget参数之后,但出现以下错误:

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

如何将@Valid注释应用于@RequestBody参数,然后获取结果?

PS,我annotation-driven用来处理控制器的接线,进行内容协商等。


问题答案:

您正在使用Spring 3.1吗?它是Spring
3.1中的新增功能。请参见验证@RequestBody方法参数