Posts Tagged ‘utf-8’

UTF-8 encoding and Spring message sources

Thursday, April 2nd, 2009

I was working on a pretty much straight-forward web application. As usual, i used Spring’s org.springframework.context.MessageSourcesupport, to be more precise, i used standard implementation – ResourceBundleMessageSource. Simple configuration, as following:

<bean id="messageSource"
                 class="org.springframework.context.support.ResourceBundleMessageSource">
          <property name="basename" value="messages"/>
</bean>

My messages properties file was standard as well, country names, so i had something like this:

country.name.unitedkindom=UK
country.name.ireland=Ireland
country.name.belgium=België
country.name.iceland=Ísland
country.name.israel=Israel...

As you can guess, the problems developed with specific characters in country names(ë, Í…). When i run the application, i got ‘???’ characters instead of specific UTF-8 characters for countries (so ‘België’ become ‘Belgi???’).

After some research, and digging in Spring source code, i located the problem, and the solution!

The problem was that ResourceBundleMessageSource uses the standard java.util.ResourceBundle and
java.util.Properties, which only support ISO-8859-1 encoding – so no UTF-8 encoding, no support for any special French, Spanish or Asian characters.

The solutions is very simple, and it comes with Spring as well. Use ReloadableResourceBundleMessageSource instead! Here is the correct configuration:

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

As you can see, we are now able ot set default encoding explicitelly, so the countries names in my example worked like charm. The only other change was that the basename is now specified as Resource, so i was able to use convenient classpath: identifier to specify my messages.properties wherever i need it in the source code