Spring MVC Internationalization and Localization

Internationalization:

It is the process of developing an application in such a way that it enables the localization.
For example : Application must support to have a separate messages.properties files for each locale/region.

Localization:

It is the process of adopting an internationalized application to specific regions/locales.
We can write locale specific details in the corresponding property files.

Ex : US locale specific details can be added inside messages_en.properties and German locale specific details can be added inside messages_de.properties.

Localization is very important for any web application which can be accessible in different regions.
So that users of specific regions can feel the application, user friendly and convenient within their language itself.

When the application is accessed by US users , web application displays the messages in the US language.
When the application is accessed by German users , web application displays the messages in the German language.

To enable the internationalization in spring MVC. We need to register below 3 beans in the spring context.

1 ) MessageSource

  1. <bean id="messageSource"
  2.         class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
  3.         <property name="basename" value="classpath:messages" />
  4.         <property name="defaultEncoding" value="UTF-8" />
  5.     </bean>
<bean id="messageSource"
        class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <property name="basename" value="classpath:messages" />
        <property name="defaultEncoding" value="UTF-8" />
    </bean>

ReloadableResourceBundleMessageSource bean enables the internationalization (i18N).
basename property is used to provide the location of resource bundles.
value specifies that resource bundles are located at messages_{locale}.properties.
defaultEncoding specifies the encoding used for the messages.

2)LocaleResolver

Resolves the locale based on its implementation.
It has 3 implementations

a)SessionLocaleResolver:

resolves the locale based on the predefined attribute in the session.

b)CookieLocaleResolver :

resolves the locale based on the predefined attribute in the cookie.

c)AcceptHeaderLocaleResolver :

default implementation which resolves the locale by checking accept-language header in the HTTP request.

If we don’t define any locale resolvers , spring by default takes AcceptHeaderLocaleResolver.

Lets implement SessionLocaleResolver in our application.

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

3) LocaleChangeInterceptor

This interceptor intercept the HTTP request and checks for the special parameter in the request.
The name of the parameter that it has to check in the request can be specified by the property called paramName, its value will be searched in the HTTP request by this interceptor.

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

So here , it searches for the parameter language in the HTTP request.
Its value in the request is the locale value which it will add in the place of {locale} in the line messages_ {locale} and seraches for the corresponding messages property file.


Lets create the Spring MVC project for 2 locales , US and Germany.

Project structure

Create the 2 messages.properties files one for each locale.

messages_en.properties

  1. label.userName=User Name
  2. label.password = Password
  3. label.login.header=Enter below details to login
  4. label.login.submit=Submit
  5. login.success.title = Login Success
  6. login.success.welcome = Welcome {0}
label.userName=User Name
label.password = Password
label.login.header=Enter below details to login
label.login.submit=Submit
login.success.title = Login Success
login.success.welcome = Welcome {0}

messages_de.properties

  1. label.userName= Benutzername
  2. label.password = Passwort
  3. label.login.header=eingeben unten Einzelheiten bis Einloggen
  4. label.login.submit=einreichen
  5. login.success.title Einloggen Erfolg
  6. login.success.welcome = willkommen {0}
label.userName= Benutzername
label.password = Passwort
label.login.header=eingeben unten Einzelheiten bis Einloggen
label.login.submit=einreichen
login.success.title Einloggen Erfolg
login.success.welcome = willkommen {0}

Create spring configuration file by adding beans required to enable Internationalization.

Spring-mvc.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
  4.     xmlns:context="http://www.springframework.org/schema/context"
  5.     xmlns:mvc="http://www.springframework.org/schema/mvc"
  6.     xsi:schemaLocation="http://www.springframework.org/schema/beans
  7.        http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
  8.        http://www.springframework.org/schema/context
  9.        http://www.springframework.org/schema/context/spring-context-3.2.xsd
  10.        http://www.springframework.org/schema/mvc
  11.        http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
  12.  
  13.     <context:component-scan base-package="com.kb.*" />
  14.     <mvc:annotation-driven />
  15.  
  16.     <bean id="viewResolver"
  17.         class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  18.         <property name="prefix" value="/WEB-INF/pages/" />
  19.         <property name="suffix" value=".jsp" />
  20.     </bean>
  21.  
  22.     <bean id="messageSource"
  23.         class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
  24.         <property name="basename" value="classpath:messages" />
  25.         <property name="defaultEncoding" value="UTF-8" />
  26.     </bean>
  27.  
  28.     <bean id="localeResolver"
  29.         class="org.springframework.web.servlet.i18n.SessionLocaleResolver">
  30.         <property name="defaultLocale" value="en" />
  31.     </bean>
  32.  
  33.     <mvc:interceptors>
  34.         <bean id="localeChangeInterceptor"
  35.             class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
  36.             <property name="paramName" value="language" />
  37.         </bean>
  38.     </mvc:interceptors>
  39. </beans>
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.2.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">

	<context:component-scan base-package="com.kb.*" />
	<mvc:annotation-driven />

	<bean id="viewResolver"
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/pages/" />
		<property name="suffix" value=".jsp" />
	</bean>

	<bean id="messageSource"
		class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
		<property name="basename" value="classpath:messages" />
		<property name="defaultEncoding" value="UTF-8" />
	</bean>

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

	<mvc:interceptors>
		<bean id="localeChangeInterceptor"
			class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
			<property name="paramName" value="language" />
		</bean>
	</mvc:interceptors>
</beans>

Now Define the View pages

login.jsp

  1. <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
  2. <%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
  3. <html>
  4. <head>
  5. <title>Spring MVC Exception Handling</title>
  6. </head>
  7.  
  8. <body>
  9.     <h2><spring:message code="label.login.header"/></h2>
  10.  
  11.     <form:form method="POST" modelAttribute="user" action="doLogin">
  12.         <table>
  13.            
  14.             <tr>
  15.                 <td><spring:message code="label.userName"/></td>
  16.                 <td><form:input path="userName" /></td>
  17.             </tr>
  18.            
  19.             <tr>
  20.                 <td><spring:message code="label.password"/></td>
  21.                 <td><form:password path="password"  showPassword="true"/></td>
  22.             </tr>
  23.            
  24.             <tr>
  25.                 <td><input type="submit" name="submit" value=<spring:message code="label.login.submit"/>></td>
  26.             </tr>
  27.         </table>
  28.     </form:form>
  29.  
  30. </body>
  31. </html>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<html>
<head>
<title>Spring MVC Exception Handling</title>
</head>

<body>
	<h2><spring:message code="label.login.header"/></h2>

	<form:form method="POST" modelAttribute="user" action="doLogin">
		<table>
			
			<tr>
				<td><spring:message code="label.userName"/></td>
				<td><form:input path="userName" /></td>
			</tr>
			
			<tr>
				<td><spring:message code="label.password"/></td>
				<td><form:password path="password"  showPassword="true"/></td>
			</tr>
			
			<tr>
				<td><input type="submit" name="submit" value=<spring:message code="label.login.submit"/>></td>
			</tr>
		</table>
	</form:form>

</body>
</html>

home.jsp

  1. <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
  2.     pageEncoding="ISO-8859-1"%>
  3. <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
  4. <%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
  5. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  6. <html>
  7. <head>
  8. <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
  9. <title><spring:message code="login.success.title"/></title>
  10. </head>
  11. <body>
  12.  <div align="center">
  13.        <h2><spring:message code="login.success.welcome" arguments="${user.userName}"/></h2>
  14.   </div>
  15. </body>
  16. </html>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title><spring:message code="login.success.title"/></title>
</head>
<body>
 <div align="center">
       <h2><spring:message code="login.success.welcome" arguments="${user.userName}"/></h2>
  </div>
</body>
</html>

Here this line

  1.  <spring:message code="key in property file"/>
 <spring:message code="key in property file"/> 

loads the property from the corresponding message property file based on the language parameter passed.

LoginController.java to handle login requests

  1. package com.kb.controllers;
  2.  
  3. import org.springframework.stereotype.Controller;
  4. import org.springframework.ui.Model;
  5. import org.springframework.web.bind.annotation.ModelAttribute;
  6. import org.springframework.web.bind.annotation.RequestMapping;
  7. import org.springframework.web.bind.annotation.RequestMethod;
  8.  
  9. import com.kb.model.User;
  10.  
  11. @Controller
  12. public class LoginController {
  13.  
  14.     @RequestMapping(value="/displayLoginPage",method=RequestMethod.GET)
  15.     public String displayLoginPage(Model model){
  16.         User user = new User();
  17.         model.addAttribute("user", user);
  18.         return "/login";
  19.     }
  20.    
  21.     @RequestMapping(value="/doLogin",method=RequestMethod.POST)
  22.     public String doLogin(@ModelAttribute User user,Model model){
  23.        
  24.         String userName=user.getUserName();
  25.         String password = user.getPassword();
  26.         if("kb".equals(userName) && "1234".equals(password)){
  27.             model.addAttribute("user", user);
  28.             return "/home";
  29.         }
  30.         return "/login";
  31.        
  32.     }
  33.    
  34. }
package com.kb.controllers;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.kb.model.User;

@Controller
public class LoginController {

	@RequestMapping(value="/displayLoginPage",method=RequestMethod.GET)
	public String displayLoginPage(Model model){
		User user = new User();
		model.addAttribute("user", user);
		return "/login";
	}
	
	@RequestMapping(value="/doLogin",method=RequestMethod.POST)
	public String doLogin(@ModelAttribute User user,Model model){
		
		String userName=user.getUserName();
		String password = user.getPassword();
		if("kb".equals(userName) && "1234".equals(password)){
			model.addAttribute("user", user);
			return "/home";
		}
		return "/login";
		
	}
	
}

web.xml

  1. <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  2.     xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
  3.     version="3.1">
  4.  
  5.     <display-name>Spring Localization</display-name>
  6.  
  7.     <!-- Spring MVC dispatcher servlet -->
  8.     <servlet>
  9.         <servlet-name>mvc-dispatcher</servlet-name>
  10.         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  11.         <init-param>
  12.             <param-name>contextConfigLocation</param-name>
  13.             <param-value>
  14.             /WEB-INF/spring-mvc.xml,
  15.         </param-value>
  16.         </init-param>
  17.         <load-on-startup>1</load-on-startup>
  18.     </servlet>
  19.     <servlet-mapping>
  20.         <servlet-name>mvc-dispatcher</servlet-name>
  21.         <url-pattern>/</url-pattern>
  22.     </servlet-mapping>
  23.  
  24.     <listener>
  25.         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  26.     </listener>
  27. </web-app>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
	version="3.1">

	<display-name>Spring Localization</display-name>

	<!-- Spring MVC dispatcher servlet -->
	<servlet>
		<servlet-name>mvc-dispatcher</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>
			/WEB-INF/spring-mvc.xml,
		</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>mvc-dispatcher</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>

	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
</web-app>

pom.xml

  1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  2.   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  3.   <modelVersion>4.0.0</modelVersion>
  4.   <groupId>Spring</groupId>
  5.   <artifactId>Spring_Localization</artifactId>
  6.   <packaging>war</packaging>
  7.   <version>0.0.1-SNAPSHOT</version>
  8.   <name>Spring_Localization Maven Webapp</name>
  9.   <url>http://maven.apache.org</url>
  10.    <properties>
  11.         <org.springframework.version>4.2.0.RELEASE</org.springframework.version>
  12.     </properties>
  13.   <dependencies>
  14.     <dependency>
  15.       <groupId>junit</groupId>
  16.       <artifactId>junit</artifactId>
  17.       <version>3.8.1</version>
  18.       <scope>test</scope>
  19.     </dependency>
  20.     <dependency>
  21.             <groupId>org.springframework</groupId>
  22.             <artifactId>spring-web</artifactId>
  23.             <version>${org.springframework.version}</version>
  24.         </dependency>
  25.  
  26.         <dependency>
  27.             <groupId>org.springframework</groupId>
  28.             <artifactId>spring-webmvc</artifactId>
  29.             <version>${org.springframework.version}</version>
  30.         </dependency>
  31.         <dependency>
  32.             <groupId>javax.servlet</groupId>
  33.             <artifactId>servlet-api</artifactId>
  34.             <version>2.5</version>
  35.             <scope>provided</scope>
  36.         </dependency>
  37.         <dependency>
  38.     <groupId>javax.servlet.jsp.jstl</groupId>
  39.     <artifactId>javax.servlet.jsp.jstl-api</artifactId>
  40.     <version>1.2.1</version>
  41. </dependency>
  42. <dependency>
  43.     <groupId>taglibs</groupId>
  44.     <artifactId>standard</artifactId>
  45.     <version>1.1.2</version>
  46. </dependency>
  47.   </dependencies>
  48.   <build>
  49.     <finalName>SpringLocalization</finalName>
  50.     <plugins>
  51.             <plugin>
  52.                 <groupId>org.apache.maven.plugins</groupId>
  53.                 <artifactId>maven-compiler-plugin</artifactId>
  54.                 <version>2.5.1</version>
  55.                 <configuration>
  56.                     <source>1.8</source>
  57.                     <target>1.8</target>
  58.                 </configuration>
  59.             </plugin>
  60.         </plugins>
  61.   </build>
  62. </project>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>Spring</groupId>
  <artifactId>Spring_Localization</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>Spring_Localization Maven Webapp</name>
  <url>http://maven.apache.org</url>
   <properties>
		<org.springframework.version>4.2.0.RELEASE</org.springframework.version>
	</properties>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>${org.springframework.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${org.springframework.version}</version>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>2.5</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
	<groupId>javax.servlet.jsp.jstl</groupId>
	<artifactId>javax.servlet.jsp.jstl-api</artifactId>
	<version>1.2.1</version>
</dependency>
<dependency>
	<groupId>taglibs</groupId>
	<artifactId>standard</artifactId>
	<version>1.1.2</version>
</dependency>
  </dependencies>
  <build>
    <finalName>SpringLocalization</finalName>
    <plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>2.5.1</version>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
				</configuration>
			</plugin>
		</plugins>
  </build>
</project>

Now Localization is done in the application.

Spring looks for the parameter language in the HTTP request as we configured.
And loads the corresponding message property file.

Deploy the application and Let’s access below url

http://localhost:8080/SpringLocalization/displayLoginPage

Here in the Request URL, we have not passed the configured locale parameter, so it takes default as en as we have specified in spring configuration file.

Input username as kb and password as 1234

see below output

Now try to pass the German locale in the HTTP request as below

http://localhost:8080/SpringLocalization/displayLoginPage?language=de

All the messages in this page are appearing in German language as they are getting loaded by messages_de.properties file.

Input username as kb and password as 1234

Click on submit

Now try to access the below url where we are not passing language parameter and check the output

http://localhost:8080/SpringLocalization/displayLoginPage

The output is shown in the German locale, even though we have not passed the language=de parameter in the second request, It still refers to language as de.

This is happening because of our SessionLocaleResolver which keeps the current locale throughout the session if we don’t pass any locale explicitly.

How to load the property from messages property file in the java file ?

We need to autowire MessageSource inside the java class where we need to load the property and we can access the required property as below

  1. @Controller
  2. public class LoginController {
  3.    
  4.     @Autowired
  5.     MessageSource messageSource;
  6.  
  7.     @RequestMapping(value="/displayLoginPage",method=RequestMethod.GET)
  8.     public String displayLoginPage(Model model){
  9.         User user = new User();
  10.         model.addAttribute("user", user);
  11.         return "/login";
  12.     }
  13.    
  14.     @RequestMapping(value="/doLogin",method=RequestMethod.POST)
  15.     public String doLogin(@ModelAttribute User user,Model model){
  16.        
  17.         String userName=user.getUserName();
  18.         String password = user.getPassword();
  19.         if("kb".equals(userName) && "1234".equals(password)){
  20.             model.addAttribute("user", user);
  21.             return "/home";
  22.         }
  23.         String loginSuccessWelcome = messageSource.getMessage("login.success.welcome", new Object[]{user.getUserName()}, LocaleContextHolder.getLocale());
  24.         System.out.println(loginSuccessWelcome);
  25.         return "/login";
  26.        
  27.     }
@Controller
public class LoginController {
	
	@Autowired
	MessageSource messageSource;

	@RequestMapping(value="/displayLoginPage",method=RequestMethod.GET)
	public String displayLoginPage(Model model){
		User user = new User();
		model.addAttribute("user", user);
		return "/login";
	}
	
	@RequestMapping(value="/doLogin",method=RequestMethod.POST)
	public String doLogin(@ModelAttribute User user,Model model){
		
		String userName=user.getUserName();
		String password = user.getPassword();
		if("kb".equals(userName) && "1234".equals(password)){
			model.addAttribute("user", user);
			return "/home";
		}
		String loginSuccessWelcome = messageSource.getMessage("login.success.welcome", new Object[]{user.getUserName()}, LocaleContextHolder.getLocale());
		System.out.println(loginSuccessWelcome);
		return "/login";
		
	}

messageSource.getMessage method is called by passing below arguments

1)Key in the property file , in our case it is login.success.welcome
2)Argument that needs to be added dynamically to the property value , in our case we have just one argument userName
3)Locale – the locale from which it has to load the property.

Now when we run the above project with this controller and access the home page
We will get the property value loaded from the corresponding locale as below

Download this project Spring_Localization.zip

About the Author

Founder of javainsimpleway.com
I love Java and open source technologies and very much passionate about software development.
I like to share my knowledge with others especially on technology 🙂
I have given all the examples as simple as possible to understand for the beginners.
All the code posted on my blog is developed,compiled and tested in my development environment.
If you find any mistakes or bugs, Please drop an email to kb.knowledge.sharing@gmail.com

Connect with me on Facebook for more updates

Share this article on