【问题标题】:Using Spring's MessageSource for setting FieldError default messages使用 Spring 的 MessageSource 设置 FieldError 默认消息
【发布时间】:2012-10-30 07:30:35
【问题描述】:

验证表单支持对象后,我有一个 BindingResult,其中包含一个 FieldError 列表。每个 FieldError 都有一个 defaultMessage。该消息是如何设置的,为什么不使用我的 Spring MessageSource?我希望从我的 Spring 的 MessageSource 派生该默认消息。

编辑: 我看到在 FieldError 对象中正确设置了错误代码。这只是该对象中的默认消息不是来自我的 MessageSource。例如,当我为一个 int 字段输入一个字符串时,我希望它从 messages.properties 中获取我的消息:

typeMismatch=Invalid type was entered.

获取该消息的唯一方法是获取我的 FieldError 对象并将其手动传递到 MessageSource 中,如下所示:

messageSource.getMessage(fieldError, null);  // This gets my message from messages.properties.

【问题讨论】:

  • 这个问题你解决了吗?
  • 对不起,我不记得我们最终在那个项目上做了什么。不幸的是,我也无法再访问该项目的源代码了。

标签: spring validation spring-mvc bean-validation


【解决方案1】:

如果您使用Validator,您可以在Validator 实现类的MessageSource 中指定消息的键,通常使用ValidationUtils 方法。 Section 6.2 of the Spring documentation 有一个很好的例子。

如果您使用的不是像 JSR-303 Bean Validation 这样的验证器,Spring 也会按照约定尝试 resolve error codes

假设您有一个名为“Address”的表单支持对象,其中包含一个名为“zipcode”的 int 字段。如果用户为 zipcode 字段输入了字符串,默认情况下 Spring 将使用 DefaultMessageCodesResolver 并在 MessageSource 中查找名为“typeMismatch.address.zipcode”的键。如果没有找到该键,它将尝试“typeMismatch.zipcode”,然后是“typeMismatch.int”,然后是“typeMismatch”。

或者,您可以实现自己的MessageCodesResolver

【讨论】:

  • 我可以看到在 FieldError 对象中设置了正确的错误代码。只是该对象中的默认消息不是来自我的 MessageSource。我必须调用 messageSource.getMessage(fieldError, null) 来获取我的消息。我希望 FieldError 对象中的默认消息自动来自我的 MessageSource。
  • 您能否添加一些更具体的代码示例来引用您遇到问题的对象属性?也许是 bean 注释、消息键等?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-10-30
  • 1970-01-01
  • 1970-01-01
  • 2010-11-25
  • 1970-01-01
  • 2017-05-27
  • 1970-01-01
相关资源
最近更新 更多