Spring MVC custom errors and internationalization

寵の児 提交于 2019-12-08 04:05:12

问题


In my web application, I handle errors with annotations. Everything works fine and I can use custom messages via the "message" parameter.

@Digits(fraction = 0, integer = 3, message="my custom error message...")
private String price;

Now I'm trying to internationalize this message with a .properties files, but I certainly miss something and I can't get it to work.

My spring config :

<beans:bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
    <beans:property name="basenames" value="classpath:i18n/messages, classpath:i18n/errors" />
    <beans:property name="defaultEncoding" value="UTF-8" />
</beans:bean>

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

<beans:bean id="localeResolver" class="org.springframework.web.servlet.i18n.FixedLocaleResolver">
    <beans:property name="defaultLocale" value="fr" />
</beans:bean>

My new bean :

@Digits(fraction = 0, integer = 3)
private String price;

My "errors_fr.properties" file. I've already tried everything :

Digits.myBean.myNestedBean.price = my custom error message...
Digits.myNestedBean.price = my custom error message...
javax.validation.constraints.Digits.myNestedBean.price = my custom error message...

I always get the same generic message from spring, it's like as spring doesn't detect my .properties file. By the way, the message keys above can be found in the BindingResult object when debugging.

What am I missing here ?

Notice that I already have internationalized messages in my jsp's (in the "messages_fr.properties" file) and they work fine.


回答1:


I had a similar problem in my application, and I hope that this can help you.

As discussed in this thread, http://forum.springsource.org/showthread.php?73240-Roo-JSR-303-Validations-and-Localization, you need to:

  1. define the error messages referred by the annotation in file ValidationMessages.properties
  2. in your annotation, refer to the error message key enclosed in curly brackets:

@Digits(fraction = 0, integer = 3, message="{message.key}")

Hope this helps.



来源:https://stackoverflow.com/questions/9896917/spring-mvc-custom-errors-and-internationalization

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!