【问题标题】:Spring mvc bind errors internatiolizationSpring mvc 绑定错误国际化
【发布时间】:2012-11-12 18:04:27
【问题描述】:

我在解决绑定时的 typeMismatch 异常时遇到了一些问题。类型不匹配错误无法从我的 messages.properties 中解决。

我的控制器处理程序:

@RequestMapping(method = RequestMethod.POST)
public @ResponseBody
    ValidationResponse addOrder(@ModelAttribute(value = PARAM_NAME) @Valid Orders orders, BindingResult bindingResult) {
    ...
}

我从 bindingResult 收到这条消息。

弹簧配置:

...
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
    <property name="basename" value="/WEB-INF/messages" />
    <property name="defaultEncoding" value="UTF-8"/>
</bean>

<bean name="validator"
      class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
    <property name="validationMessageSource">
        <ref bean="messageSource"/>
    </property>
</bean>
...

/WEB-INF/messages.properties:

...
Orders.width.NotNull=Null error
Orders.height.NotNull=Null error
typeMismatch.java.util.Date=Format error
typeMismatch.java.lang.Integer=Format error
typeMismatch.java.lang.Long=Format error
java.lang.NumberFormatException=Format error
typeMismatch.java.lang.NumberFormatException=Format error
typeMismatch.java.lang.NumberFormat=Format error
typeMismatch.orderAdd.width=Format error
typeMismatch=Format error
...

对于这样的检查:

...
@NotNull(message="{Orders.width.NotNull}")
private Long width;
...

我收到了正确的消息。

更新

此示例打印错误消息:

List<FieldError> allErrors = bindingResult.getFieldErrors();
  for (FieldError objectError : allErrors) {
    System.out.println(objectError.getDefaultMessage());
}

【问题讨论】:

  • 消息如何显示(对于不工作的消息)?
  • 是的,我不明白在这个问题中什么有效,什么无效(或不按预期工作)
  • @Rachel G.,我更新了问题
  • 在您的更新中,“打印错误消息”是什么意思?消息说什么?
  • @Rachel G.,这只是一个例子。在实际代码中,这个经过一些修改的列表作为 JSON 发送到 JavaScript。

标签: java spring validation spring-mvc internationalization


【解决方案1】:

我在this 问题中找到了解决方案。要翻译消息,我必须注入 messageSource 并使用以下代码:

messageSource.getMessage(objectError, locale)

这会从我的属性文件中获取消息。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-15
    • 1970-01-01
    • 1970-01-01
    • 2021-04-17
    • 1970-01-01
    相关资源
    最近更新 更多