Interview Questions

Who's online

There are currently 0 users and 3 guests online.

Spring Internationalization (I18N)

In this section, let us discuss about Internationalization (i18n) in Spring application.

In any web based application, all the text in the application UI (like names, labels), success/failure error message, validation messages etc will be in common English. In some scenarios, the Customer may require to display those text in regional specific languages.

For Example, if the web application is accessed from Spain, the text and other messages should be displayed in Spanish language. Java provides inbuilt support for localization using java.util.Locale class. Now lets get in to the details of the support provided by Spring for I18N.

Initially we need to create a bean for class org.springframework.context.support.ResourceBundleMessageSource as follows in application context.

<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
        <property name="basename" value="/WEB-INF/classes/mess"/>
</bean>

The basename property represents a properties file location which contains the key value pairs of the messages to be displayed in UI. In the above case, there needs to be file mess.properties present in /WEB-INF/classes/ folder.

The alternative to above bean is org.springframework.context.support.ReloadableResourceBundleMessageSource. As the name suggests, it is re-loadable when the server is running and the cache time limit can be set.

<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <description>
                Bean for defining multiple message resource bundles
        </description>
        <property name="basenames" >
                <list>
                        <value>/WEB-INF/classes/mess</value>
                </list>
        </property>
        <property name="cacheSeconds" value="60"/>
</bean>

Here is a sample mess.properties file

mess.properties:

userForm.success=User Registered Successfully
userForm.failure=User Registration Failed

This file will be usually in the format mess_xx_XX.properties (xx- Language Code and XX- Country Code).

For example, mess_de_DE.properties for German language in Germany.

Now to display the message for a key in JSP, we can use JSTL tag. To display success message for user use the following tag in JSP

<fmt:message key="userForm.success"/>

Also to test the application for different regional settings, we can change the settings of the browser.

For example, in Internet Explorer go to Tools > Internet Options > General(Tab) > click Languages button and then add the new languages for different countries.