Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring uses wrong codification for customized validation messages

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.

like image 956
borjab Avatar asked Oct 20 '25 12:10

borjab


1 Answers

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

like image 96
borjab Avatar answered Oct 23 '25 07:10

borjab



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!