Question

I have a Spring form wih some validations and all the personalized messeges from javax.validation.constraints appears to use the wrong encoding.

Lets take this as an example:

@NumberFormat(style=Style.NUMBER) 
@NotNull 
private BigDecimal maintenanceCosts;

With applicationContext.xml file containing

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

<bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver">
    <property name="defaultLocale" value="en" />
</bean>

And a ValidationMessage_en.properties encoded in UTF-8 and marked so (in Eclipse with right click, properties) with the text:

javax.validation.constraints.NotNull.message=This field can't be empty

I want to show thouse messages in localized strings with the right codification so I added an UTF-8 file ValidationMessages_ru.properties with:

javax.validation.constraints.NotNull.message=Это поле не может быть пустым

But the message shows this message: Это поле не может быть пуÑтым

On the other hand I has able to customize the spring managed error messages with the right encoding. But JSR303 texts seems to behave differently.

Was it helpful?

Solution

I found that it was much more elegant to get rid of the ValidationMessages_XX.properties files. Just all the localized configuration in one file that supports UTF-8!

The answer is to set the ValidationMessageSource of your validator with your resourceBundle. For example:

<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource" 
        p:defaultEncoding="UTF-8"
        p:basenames      ="classpath:messages"/>

<!-- JSR-303 validation-->
<bean id ="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"
        p:validationMessageSource-ref="messageSource"/>

All merit must be attributed to this blog post. Not being able to read thouse characters was annoying. No more: message=\u042D\u0442\u043E \u043F\u043E\u043B\u0435 \u043D\u0435 \u043C

OTHER TIPS

Properties file in Java are per default ISO 8859-1. Characters which you cannot display this way need to use unicode escapes. To quote the javadocs of Properties:

...except the input/output stream is encoded in ISO 8859-1 character encoding. Characters that cannot be directly represented in this encoding can be written using Unicode escapes ; only a single 'u' character is allowed in an escape sequence.

You will need to use unicode escapes. You can di it manually or use native2ascii.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top