Share on Google+Share on Google+

Locale in Spring MVC

To support internationalization in spring mvc application, you need to register two beans in spring configuration xml file:

Locale in Spring MVC

To support internationalization in spring mvc application, you need to register two beans in spring configuration xml file:

1. SessionLocaleResolver

2. LocaleChangeInterceptor

SessionLocaleResolver resolves the locales by using a locale attribute from the session. It takes defaultLocale property to set the default locale.

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

LocaleChangeInterceptor allows the changing of the current locale by a configurable request parameter on every request of the user. 1paramName is the property name the value of which is used to change the locale. ie. "ln" parameter will be used to change the locale and this parameter will be sent along with the request of any resource of the application.

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

This "ln" parameter will be used like below to change the locale:

example.html?ln=en to set the locale to English and get the message from English properties file. 

example.html?ln=fr_FR to set the locale to French and get the message from French properties file.

Now reference this interceptor to any handler mapping.

<bean class="" >
       <property name="interceptors">
                  <ref bean="localeChangeInterceptor" />

Now register the properties file

<bean id="messageSource" class="">
          <property name="basename" value="message" />

Create two properties file to store messages in different languages. The file will be used as default file when the locale is set to default locale. The file name must start from "message" text then language country code separated by underscore.

1. "" to store messages in English

welcome = Welcome to Locale Example

2. "" to store messages in French

welcome = Bienvenue l'exemple Locale

In JSP, you can make link to change locale and display the text message on the page. For example,

<%@ page contentType="text/html;charset=UTF-8" %>
<%@ taglib prefix="spring" uri="" %>

<a href="?ln=en">Click to set English Language</a><br/>
<a href="?ln=fr_FR">Click to set French Language</a>

<h1><spring:message code="welcome"/></h1>


Run the application, you will see the output as below:

Click on the link to change the language to French. The output will be as below: 

Download the source code


Posted on: January 5, 2011 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.


Advertisement null