如何在Spring MVC的@RequestBody参数中使用@Valid? [英] How do I use @Valid with Spring MVC's @RequestBody parameters?

查看:915
本文介绍了如何在Spring MVC的@RequestBody参数中使用@Valid?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 @Controller 上的一个处理程序方法的参数上使用 @Valid 。我的代码如下所示:

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)

其中 Widget 是我的一个域对象的类。我使用 @RequestBody 注释来表示请求的有效内容映射到小部件(在我的测试中,请求是JSON,虽然Jackson在我的类路径上,所以我也可以使用XML)。

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

如你所见, BindingResult 参数直接在 Widget 参数后面,但是我收到以下错误:

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!

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

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

PS我使用注释驱动的来处理控制器的接线,进行内容协商等。

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

推荐答案

您是否使用Spring 3.1?它是Spring 3.1版中新增的功能。请参阅验证@RequestBody方法参数

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

这篇关于如何在Spring MVC的@RequestBody参数中使用@Valid?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆