我在解决绑定(bind)上的 typeMismatch 异常时遇到一些问题。类型不匹配错误无法从我的 messages.properties 中解决。
我的 Controller 处理程序:
@RequestMapping(method = RequestMethod.POST)
public @ResponseBody
ValidationResponse addOrder(@ModelAttribute(value = PARAM_NAME) @Valid Orders orders, BindingResult bindingResult) {
...
}
我从绑定(bind)结果中获取此消息。
Spring 配置:
...
<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());
}
最佳答案
我在 this 中找到了解决方案问题。要翻译消息,我必须注入(inject) messageSource
并使用以下代码:
messageSource.getMessage(objectError, locale)
这从我的属性文件中获取消息。
关于java - Spring mvc 绑定(bind)错误国际化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13349015/