To support internationalization in spring mvc application, you need to register two beans in spring configuration xml file:
To support internationalization in spring mvc application, you need to register two beans in spring configuration xml file: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" /> </bean> |
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" /> </bean> |
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="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"
> <property name="interceptors"> <list> <ref bean="localeChangeInterceptor" /> </list> </property> </bean> |
Now register the properties file
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource"> <property name="basename" value="message" /> </bean> |
Create two properties file to store messages in different languages. The message.properties 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. "message.properties" to store messages in English
welcome = Welcome to Locale Example |
2. "message_fr_FR.properties" 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="http://www.springframework.org/tags" %> <html> <body> <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> </body> </html> |
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: