Spring MVC Internationalization and Localization

For a web app to be able to used across languages/regions without much of major changes they must support Internationalization and Localization. In this post we will see example of Spring MVC Internationalization(i18n) and Localization(L10n).
Internationalization is a way of designing software’s so that they can be adapted in various languages and regions without much of changes.
Localization is a way of using the Internationalized software’s for a specific language/region using a specific locale.

What is i18n and L10n?

i18n for Internationalization - 18 stands for the number of letters between the first i and the last n in the word internationalization.
L10n for Localization - 10 stands for the length of the words.

Example : Spring MVC Internationalization and Localization

1. Dispatcher Servlet Configurations

a) localeResolver – is used to store the locale changes. We can either use the org.springframework.web.servlet.i18n.CookieLocaleResolver or org.springframework.web.servlet.i18n.SessionLocaleResolver for this purpose. In our example we will use the CookieLocaleResolver

b) localeChangeInterceptor – is used to intercept any changes in the locale using the parameter configured. You can choose the name of the param

c) messageSource – is configured to load the messages.

Complete dispatcher servlet

2. Message per Locale

The message files for a particluar locale are decided using a pattern.
example – if the messageSource is configured to “messages” and the localeChangeInterceptor uses a lang=fr, then the app will try to locate a message source property of name messages_fr.properties.
we have set the defaultLocale to “en”, so the name of the property file for lang=en can be either messages.properties or messages_en.properties.

We will use en and fr for our example.
messages_en.properties

messages_fr.properties

3. Changes in JSP

In JSP instead of using the hard coded values we need to use spring tags to display any text.
example instead of using “First Name” we now will use the spring tag and message code from the properties file – <spring:message code="employee.form.firstName"/>

Complete JSP

Output

Using lang=en – http://localhost:8080/sampleproject/employeeForm?lang=en
Spring MVC Internationalization and Localization

Using lang=fr – http://localhost:8080/sampleproject/employeeForm?lang=fr
Spring MVC Internationalization and Localization

Download Full Code – SpringMVCLocalization.zip

It's only fair to share...Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedIn