Errors/BindingResult 参数应紧跟在模型属性、@RequestBody或@RequestPart参数之后声明

2022-09-01 12:09:19

我正在通过剖析示例应用程序来自学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 url 模式时,触发了此错误消息。我已经查看了此页面此帖子,但解释似乎不清楚。

任何人都可以告诉我如何修复此错误,并解释它的含义吗?

编辑:
根据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";
 }

在告诉日食运行为...再次在服务器上运行。

有什么我不明白的吗?


答案 1

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

如果它没有找到一个,它就会通过(我必须验证这一点)。null

是一个 result 对象,它包含可能已出现验证 、 或 的错误,因此您只能将其与注释为此类的参数一起使用。每个注释都有。BindingResult@ModelAttribute@Valid@RequestBody@RequestPartHandlerMethodArgumentResolver

编辑(对评论的响应)

您的示例似乎表明用户应提供 pet 类型(整数)。我会将方法更改为

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

并且您将提出请求(取决于您的配置)

localhost:8080/yourcontext/catowners?type=1

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


答案 2

如果您有一个类型的参数,则在将 http 请求参数绑定到直接在 BindingResult 方法参数之前声明的变量时,实质上是保留任何错误。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, ...)

推荐