微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

java – 获取@RequestParam的BindingResult的任何方法?

我正在使用Spring 3 Portlet MVC.仅MVC中的验证/绑定应该是相同的.

我只有一个int表单字段.当我在做的时候

void doSmth(MyForm form,BindingResult bindingResult) throws ... {
  int bindErrors = bindingResult.getErrorCount())
  ...

并提交一个无法解析为int的字段值此方法执行并且bindErrors为1.此方法接收的表单字段值为0.这很好.

但是创建一个仅包含单个字段的表单并不是很好.

我正在将代码更改为:

void doSmth(@RequestParam int userId,BindingResult bindingResult) ... {
  int bindErrors = bindingResult.getErrorCount())
  ...

并在浏览器中获取Portlet不可用的消息和此异常:

org.springframework.web.portlet.FrameworkPortlet processRequest Could
not complete request
org.springframework.beans.TypeMismatchException: Failed to convert
value of type ‘java.lang.String’ to required type ‘int’; nested
exception is java.lang.NumberFormatException: For input string: “q”

问题:即使@RequestParam类型转换失败,有没有办法继续执行方法并处理绑定错误?我尝试不要求@RequestParam并为它提供认值 – 没有帮助.

最佳答案
Spring引用仅允许BindingResult用于命令或表单对象.

org.springframework.validation.Errors / org.springframework.validation.BindingResult validation results for a preceding command or form object (the immediately preceding method argument).

(15.3.2.3 Supported handler method arguments and return types)

所以你可能需要自己实现它.

>我认为您可以尝试使用Custom MethodArgumentResolver(请参阅此blog的示例).
>还有另一个当前仍然存在的堆栈溢出问题:How to customize parameter names when binding spring mvc command objects – 我觉得这个问题的解决方案可以为您的解决方案提供良好的输入.

或者将您的单个int包装在一个命令对象中并使用该对象的绑定结果(可以在此处找到一个示例:https://stackoverflow.com/a/13407434/280244)

原文地址:https://www.jb51.cc/spring/431993.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐