Saturday, February 11, 2012

Spring mvc internationalization support with cookies

Spring mvc has a great support for adding internationalization support to web applications. It allows adding support for displaying multi- messages in just several configuration settings. I have created a sample application to demonstrate one way to accomplish that. The application is available on github spring-internationalization. The app uses maven to resolve all dependencies and cargo plugin to download and run local tomcat instance. It should be fairly easy to check it out (once maven 3 is installed and configured) To try it out, make sure that maven is installed and configured properly. Pull down the app from the public github repository at spring-internationalization, open terminal window and execute following command in app root directory:
     mvn clean package cargo:run

Running this command will download, and execute a local copy of tomcat and deploy the application. Once tomcat has been started application can be accessed in web browser by going to following url:


To check out language features, select a language from "Pick language" select box, on home page. Changing select box value changes the language used in entire application (2 humble jsp pages in this particular case) and re-loads home page with messages in newly selected locale.


This is a typical spring mvc web application, so I'm going to skip describing components in detail. Below I displayed configuration pieces needed to support internationalization:
1. Message source bean - tells spring where to find resource bundles and their file name pattern. In this application file name pattern is (ie. for english/US properties files) see files in src/main/resources/bundles path in project for details.

    <bean id="messageSource" 

2. Mvc interceptor - component intercepting http requests checking whether locale needs to be changed.
This interceptor is configured to capture requests with parameter name of siteLanguage and attempts to change the locale based on parameter value:
For example a request to the home page with appended parameter value such as below
will attempt to change application language to french.

        <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor" >
            <property name="paramName" value="siteLanguage"/>

3. CookieLocaleResolver bean is the third piece of the puzzle. This bean stores locale selected by user in a browser cookie.

4. Finally jsp pages use spring:message tag to access bundle messages as listed below.


This is it in a nutshell. Note that this is just one of the strategies. Spring provides other tools for handling internationalization. One common strategy is to fallback to language settings in http request header to determine desired locale if cookie value is not available (or CookieLocaleResolver localization is not configured).

No comments:

Post a Comment