期望在模型属性@RequestBody或@RequestPart参数之后立即声明Errors / BindingResult参数

我通过剖析示例应用程序然后在这里和那里添加代码来测试我在解剖过程中开发的理论来自学Spring。 我测试一些我添加到Spring应用程序的代码时收到以下错误消息:

An Errors/BindingResult argument is expected to be declared immediately after the model attribute, the @RequestBody or the @RequestPart arguments to which they apply 

错误消息引用的方法是:

 @RequestMapping(value = "/catowners", method = RequestMethod.GET) public String findOwnersOfPetType(Integer typeID, BindingResult result, Map model) { // find owners of a specific type of pet typeID = 1;//this is just a placeholder Collection results = this.clinicService.findOwnerByPetType(typeID); model.put("selections", results); return "owners/catowners"; } 

当我尝试在Web浏览器中加载/ catowners url模式时,会触发此错误消息。 我已经回顾了这个页面和这个post ,但解释似乎并不清楚。

任何人都可以告诉我如何解决这个错误,并解释它是什么意思?

编辑:
根据Biju Kunjummen的回复,我将语法更改为以下内容:

 @RequestMapping(value = "/catowners", method = RequestMethod.GET) public String findOwnersOfPetType(@Valid Integer typeID, BindingResult result, Map model) 

我仍然收到相同的错误消息。 是不是我不理解的东西?

第二次编辑:

根据Sotirios的评论,我将代码更改为以下内容:

 @RequestMapping(value = "/catowners", method = RequestMethod.GET) public String findOwnersOfPetType(BindingResult result, Map model) { // find owners of a specific type of pet Integer typeID = 1;//this is just a placeholder Collection results = this.clinicService.findOwnerByPetType(typeID); model.put("selections", results); return "owners/catowners"; } 

告诉eclipse运行后,我仍然收到相同的错误消息…再次在服务器上运行。

有什么我不理解的东西吗?

Spring使用一个名为HandlerMethodArgumentResolver的接口来解析处理程序方法中的参数,并构造一个作为参数传递的对象。

如果找不到,则传递null (我必须validation这一点)。

BindingResult是一个结果对象,它保存可能已经validation了BindingResult@RequestPart ,因此您只能将其与带注释的参数一起使用。 每个注释都有HandlerMethodArgumentResolver

编辑(回复评论)

您的示例似乎表明用户应提供宠物类型(作为整数)。 我会改变方法

 @RequestMapping(value = "/catowners", method = RequestMethod.GET) public String findOwnersOfPetType(@RequestParam("type") Integer typeID, Map model) 

你会根据你的配置提出要求

 localhost:8080/yourcontext/catowners?type=1 

这里也没有什么可以validation,所以你不需要或不需要BindingResult 。 如果您尝试添加它,它将失败。

如果你有一个BindingResult类型的参数,它实质上是在将http请求参数绑定到直接在BindingResult方法参数之前声明的变量时保留任何错误。

所以这些都是可以接受的:

 @RequestMapping(value = "/catowners", method = RequestMethod.GET) public String findOwnersOfPetType(@Valid MyType type, BindingResult result, ...) @RequestMapping(value = "/catowners", method = RequestMethod.GET) public String findOwnersOfPetType(@ModelAttribute MyType type, BindingResult result, ...) @RequestMapping(value = "/catowners", method = RequestMethod.GET) public String findOwnersOfPetType(@RequestBody @Valid MyType type, BindingResult result, ...)