gpt4 book ai didi

java - Errors/BindingResult 参数应在模型属性、@RequestBody 或 @RequestPart 参数之后立即声明

转载 作者:IT老高 更新时间:2023-10-28 13:48:49 26 4
gpt4 key购买 nike

我通过剖析示例应用程序来自学 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 模式时触发了此错误消息。我已查看 this pagethis posting ,但解释似乎并不明确。

谁能告诉我如何解决这个错误,并解释它的含义?

编辑:
根据 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 的接口(interface)来解析处理程序方法中的参数并构造一个对象以作为参数传递。

如果没有找到,则通过 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。如果您尝试添加它,它将失败。

关于java - Errors/BindingResult 参数应在模型属性、@RequestBody 或 @RequestPart 参数之后立即声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18646121/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com