Cod*_*Med 23 java spring hibernate spring-mvc
我通过剖析示例应用程序然后在这里和那里添加代码来测试我在解剖过程中开发的理论,从而自学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
Run Code Online (Sandbox Code Playgroud)
错误消息引用的方法是:
@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";
}
Run Code Online (Sandbox Code Playgroud)
当我尝试在Web浏览器中加载/ catowners url模式时,会触发此错误消息.我已经回顾了这个页面和这个帖子,但解释似乎并不清楚.
任何人都可以告诉我如何解决这个错误,并解释它是什么意思?
编辑:
基于Biju Kunjummen的回复,我将语法更改为以下内容:
@RequestMapping(value = "/catowners", method = RequestMethod.GET)
public String findOwnersOfPetType(@Valid Integer typeID, BindingResult result, Map<String, Object> model)
Run Code Online (Sandbox Code Playgroud)
我仍然收到相同的错误消息.是不是我不理解的东西?
第二次编辑:
根据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";
}
Run Code Online (Sandbox Code Playgroud)
告诉eclipse运行后,我仍然得到相同的错误消息...再次在服务器上运行.
有什么我不理解的东西吗?
Sot*_*lis 18
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)
Run Code Online (Sandbox Code Playgroud)
并且你会提出你的要求(取决于你的配置)
localhost:8080/yourcontext/catowners?type=1
Run Code Online (Sandbox Code Playgroud)
这里也没有什么可以验证,所以你不需要或不需要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, ...)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
31131 次 |
| 最近记录: |