预期在模型属性,@ 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<String, Object> model) {
// find owners of a specific type of pet
typeID = 1;//this is just a placeholder
Collection<Owner> results = this.clinicService.findOwnerByPetType(typeID);
model.put("selections", results);
return "owners/catowners";
}
当我尝试在Web浏览器中加载/
catowners网址格式时,触发了此错误消息。我已经审查了此页面和此帖子,但解释似乎不清楚。
谁能告诉我如何解决此错误,并解释其含义?
编辑:
基于Biju Kunjummen的响应,我将语法更改为以下内容:
@RequestMapping(value = "/catowners", method = RequestMethod.GET)
public String findOwnersOfPetType(@Valid Integer typeID, BindingResult result, Map<String, Object> model)
我仍然收到相同的错误消息。还有我不理解的东西吗?
第二编辑:
基于Sotirios的评论,我将代码更改为以下内容:
@RequestMapping(value = "/catowners", method = RequestMethod.GET)
public String findOwnersOfPetType(BindingResult result, Map<String, Object> model) {
// find owners of a specific type of pet
Integer typeID = 1;//this is just a placeholder
Collection<Owner> results = this.clinicService.findOwnerByPetType(typeID);
model.put("selections", results);
return "owners/catowners";
}
告诉eclipse运行为…在服务器上再次运行后,我仍然收到相同的错误消息。
有我不明白的东西吗?
问题答案:
Spring使用一个称为的接口HandlerMethodArgumentResolver
来解析您的处理程序方法中的参数,并构造一个对象作为参数传递。
如果找不到,它就会通过null
(我必须对此进行验证)。
该BindingResult
是保存可能已经拿出了一个验证错误,结果对象@ModelAttribute
,@Valid
,@RequestBody
或者@RequestPart
,这样你就可以只与这样的注释参数使用它。还有HandlerMethodArgumentResolver
为每个注释。
编辑(回复评论)
您的示例似乎表明,用户应提供宠物类型(作为整数)。我将方法更改为
@RequestMapping(value = "/catowners", method = RequestMethod.GET)
public String findOwnersOfPetType(@RequestParam("type") Integer typeID, Map<String, Object> model)
然后您将根据您的请求(取决于您的配置)
localhost:8080/yourcontext/catowners?type=1
在这里也没有任何要验证的内容,因此您不需要或不需要BindingResult
。如果您仍然尝试添加它,它将失败。