Spring Boot Internationalization Example

Introduction

Spring Boot Internationalization Example will show you how to make an web based application in different languages. Internationalization or Localization will render the web page content based on your chosen language in which you want to view the page. At present though browser gives you an option to translate the page into other language using which you browse the web page most frequently.

I will show here how we can switch in different langugaes like Bengali, Hindi, English, Dutch and French.

Though you don’t need to change the language settings from the browser for switching to different languages. You are given an option to choose a language in a dropdown where the languages are displayed in Bengali, Hindi, English, Dutch and French.

If you want you can add more languages or remove languages and accordingly you need to create separate properties file for each language and put them under classpath directory.

This application shows title, welcome message, choose language option and copyright information in Bengali, Hindi, English, Dutch and French languages.

By default the selected language is English.

Related Posts:

Prerequisites

Eclipse 4.12, JDK 8 or 12, Gradle 4.x or 5.6, Spring Boot 1.5.9 or 2.1.8

Creating Project

First create a Gradle project (name – spring-internationalization) in Eclipse and modify the build script to use below build script.

Here in the below build script we have added few dependencies such as Spring Boot, JSTL and tomcat-embed-jasper is required to view the JSP pages on browser otherwise you will get file saving option for JSP pages.

For Spring Boot 2.1.8

buildscript {
	ext {
		springBootVersion = '2.1.8.RELEASE'
	}
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
    }
}

apply plugin: 'java'
apply plugin: 'org.springframework.boot'

sourceCompatibility = 12
targetCompatibility = 12

repositories {
    mavenCentral()
}

dependencies {
	implementation("org.springframework.boot:spring-boot-starter-web:${springBootVersion}")
	implementation('org.apache.tomcat.embed:tomcat-embed-jasper:9.0.26')
    implementation('javax.servlet:jstl:1.2')
}

For Spring Boot 1.5.9

buildscript {
	 ext {
		springBootVersion = '1.5.9.RELEASE'
	 }
	 
    repositories {
		mavenLocal()
        mavenCentral()
    }
	
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
    }
}

apply plugin: 'java'
apply plugin: 'org.springframework.boot'

sourceCompatibility = 1.8
targetCompatibility = 1.8

repositories {
 mavenLocal()
    mavenCentral()
}

dependencies {
	compile("org.springframework.boot:spring-boot-starter-web:${springBootVersion}")
	compile('org.apache.tomcat.embed:tomcat-embed-jasper:8.5.14')
    compile('javax.servlet:jstl:1.2')
}

Configuring View Resolver

We have also specified the view resolver for spring boot web application. The prefix identifies the location of the view files and suffix identifies the file type, i.e., here the view files are jsp files.

#view resolver
spring.mvc.view.prefix=/views/
spring.mvc.view.suffix=.jsp

Create Language Properties

Now we will create different properties files, for spring boot internationalization example, which will identify the messages we want to display on browser in different languages.

Here we have kept messages in key/value pairs.

The different language properties files are kept under src/main/resources/i18n folder.

Bengali Messages

The content gets displayed in bengali language when you select the bengali locale from the dropdown.

The below content in key/value pairs is put into messages_bn.properties.

msg=Spring Boot MVC \u098F \u0986\u09A8\u09CD\u09A4\u09B0\u09CD\u099C\u09BE\u09A4\u09BF\u0995\u09BE\u09AF\u09BC\u09A8 \u0989\u09A6\u09BE\u09B9\u09B0\u09A3
welcome=\u09AC\u09BE\u0982\u09B2\u09BE \u09AD\u09BE\u09B7\u09BE \u09B8\u09CD\u09AC\u09BE\u0997\u09A4\u09AE
chooseLang=\u0986\u09AA\u09A8\u09BE\u09B0 \u09AD\u09BE\u09B7\u09BE \u099A\u09AF\u09BC\u09A8 \u0995\u09B0\u09C1\u09A8
copyright=\u0995\u09AA\u09BF\u09B0\u09BE\u0987\u099F
year=\u09E8\u09E6\u09E7\u09EA - \u09E8\u09E6\u09E7\u09EF

Hindi Messages

The content gets displayed in hindi language when you select the hindi locale from the dropdown.

The below content in key/value pairs is put into messages_hi.properties.

msg=Spring Boot MVC \u092E\u0947\u0902 \u0905\u0902\u0924\u0930\u094D\u0930\u093E\u0937\u094D\u091F\u094D\u0930\u0940\u092F\u0915\u0930\u0923 \u0909\u0926\u093E\u0939\u0930\u0923
welcome=\u0939\u093F\u0928\u094D\u0926\u0940 \u092D\u093E\u0937\u093E \u092E\u0947\u0902 \u0906\u092A\u0915\u093E \u0938\u094D\u0935\u093E\u0917\u0924 \u0939\u0948
chooseLang=\u0905\u092A\u0928\u0940 \u092D\u093E\u0937\u093E \u091A\u0941\u0928\u0947\u0902
copyright=\u0938\u0930\u094D\u0935\u093E\u0927\u093F\u0915\u093E\u0930
year=\u0968\u0966\u0967\u096A - \u0968\u0966\u0967\u096F

French Messages

The content gets displayed in french language when you select the french locale from the dropdown.

The below content in key/value pairs is put into messages_fr.properties.

msg=Internationalisation exemple dans Spring Boot MVC
welcome=Bienvenue à la langue française
chooseLang=Choisissez votre langue
copyright=Droit d'auteur
year=2014 - 2019

Dutch Messages

The content gets displayed in dutch language when you select the dutch locale from the dropdown.

The below content in key/value pairs is put into messages_nl.properties.

msg=Internationalisering Voorbeeld in Spring Boot MVC
welcome=Welkom bij Nederlandse Taal
chooseLang=Kies uw taal
copyright=Auteursrecht
year=2014 - 2019

English Messages

This is the default language in which the content gets displayed on the browser.

The below content in key/value pairs is put into messages.properties.

msg=Internationalization Example in Spring Boot MVC
welcome=Welcome to English Language
chooseLang=Choose your language
copyright=Copyright
year=2014 - 2018

Creating Config Class

The below application configuration class defines Spring beans for loading messages in the chosen language and LocalResolver for handling locales. By default we set English as the default page language.

We have overridden the addInterceptor() method to pass a parameter called lang in the URL, which will give us the value of the current locale selected from the locale dropdown.

package com.roytuts.spring.internationalization.config;

import java.util.Locale;

import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.i18n.CookieLocaleResolver;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;

@Configuration
public class SpringInternationalizationConfig implements WebMvcConfigurer {

	@Bean
	public MessageSource messageSource() {
		ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
		messageSource.setBasename("classpath:i18n/messages");
		messageSource.setDefaultEncoding("UTF-8");
		return messageSource;
	}

	@Bean
	public LocaleResolver localeResolver() {
		CookieLocaleResolver lr = new CookieLocaleResolver();
		lr.setDefaultLocale(Locale.US);
		return lr;
	}

	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		LocaleChangeInterceptor interceptor = new LocaleChangeInterceptor();
		interceptor.setParamName("lang");
		registry.addInterceptor(interceptor);
	}

}

Creating Controller Class

The below controller class just maps the URL with the view and the corresponding view file’s output gets displayed on the browser.

We have put the @Controller annotation on the class to make it Spring controller.

package com.roytuts.spring.internationalization.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class SpringInternationalizationController {

	@GetMapping("/")
	public String view() {
		return "i18n";
	}

}

Creating Main Class

Create below main class to startup the Spring Boot application and deploy into embedded Tomcat server.

We have specified the base package so that all classes which are annotated with spring annotation will automatically be detected by the Spring container.

package com.roytuts.spring.internationalization;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication(scanBasePackages = "com.roytuts.spring.internationalization")
public class SpringInternationalizationApp {

	public static void main(String[] args) {
		SpringApplication.run(SpringInternationalizationApp.class, args);
	}

}

Creating View File

Create below view JSP page to see in action on spring boot internationalization example and this page is responsible for displaying the expected output on the browser.

In this file we have used jQuery API to set values dynamically to the dropdown. We are also used the JavaScript’s localStorage to set the default language as English when no language is selected for the first time. We have used Spring’s tag library to create the dropdown field.

<%@ page language="java" contentType="text/html; charset=UTF-8"
                pageEncoding="UTF-8"%>
<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<head>

	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
	<meta name="viewport" content="width=device-width, initial-scale=1">
	
	<title><spring:message code="msg" /></title>
	
	<script src="https://code.jquery.com/jquery-3.4.1.js"></script>
	
	<script type="text/javascript">
		$(document).ready(function() {
			var selItem = localStorage.getItem("locales");
			$('#locales').val(selItem ? selItem : 'en');
			$("#locales").change(function() {
				var selectedOption = $('#locales').val();
				if (selectedOption) {
					window.location.replace('?lang=' + selectedOption);
					localStorage.setItem("locales", selectedOption);
				}
			});
		});
	</script>
	
	<style>
		legend {
			width: auto;
			margin-left: auto;
			margin-right: auto;
		}
	</style>
</head>
<body>
	<div style="width: 600px; margin: auto;">
		<fieldset>
			<legend>
				<spring:message code="msg" />
			</legend>
			<p>
				<label><spring:message code="chooseLang" /></label>   <select
					id="locales">
					<option value="en">English</option>
					<option value="bn">বাংলা</option>
					<option value="hi">हिंदी</option>
					<option value="fr">Français</option>
					<option value="nl">Nederlands</option>
				</select>
			</p>
		</fieldset>
		<div style="clear: both"></div>
		<div>
			<spring:message code="copyright" />
			 ©
			<spring:message code="year" />
		</div>
	</div>
</body>

Testing the Application

Let’s see the spring boot internationalization example in action.

Now start the main class and check the output by choosing different language from the dropdown.

By default when you it the URL http://localhost:8080, you will see the content is rendered in English language.

English

This default language is English the content on web pages shown by default in English.

spring boot internationalization example

Bengali

Choosing a Bengali language from dropdown will display the content in Bengali language.

spring boot internationalization example

Hindi

Choosing Hindi language from dropdown will show you this page:

spring boot internationalization example

French

Choosing French language from dropdown will show you this page:

spring boot internationalization example

Dutch

Choosing Dutch language from dropdown will show you this page:

spring boot internationalization example

Related Posts:

Source Code

You can download source code.

Thanks for reading.

Leave a Reply

Your email address will not be published. Required fields are marked *