Spring Boot Internationalization Example will show you how to make an web based application in different languages. Internationalization or Localization will show you the web page content based on your choosen language in which you want to view the page.

I will show here how we can switch in different langugaes like Bengali, Hindi, English, Dutch and French. 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 langugaes 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.

You may also would like to read JSF 2 Internationalisation Example

Prerequisites

Knowledge of:

Java
Spring
HTML

Softwares

JDK 1.8
Gradle 4.x
Spring Dependencies
JSP, JSTL Dependencies

Setting up and creating project

First create a Gradle project 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.

We have also mentioned the main class though it does not exist right now but, you can add one main class in the specified package in order to resolve the build issue.

We have specified the executable jar output name – SpringBootMvcI18N and version is 0.0.1-SNAPSHOT. You may choose jar name and version according to your choice.

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'

jar {
    baseName = 'SpringBootMvcI18N'
    version = '0.0.1-SNAPSHOT'
    manifest {
        attributes("Main-Class": "com.jeejava.main.Application")
    }
}

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')
}

Project structure

The final project structure for spring boot internationalization example would look like something similar to the below image:

spring boot internationalization example

Changing the default port

We do not want to start the server on default port 8080 of Tomcat server to avoid any collision, so we have updated the port 9999 for Tomcat server.

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.

#start server at below port
server.port=9999

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

Create language files in different languages

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.

Bengali Messages

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

i18n/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=2018

Hindi Messages

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

i18n/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=2018

French Messages

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

i18n/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=2018

Dutch Messages

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

i18n/messages_nl.properties

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

English Messages

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

i18n/messages.properties

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

Creating Application 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.jeejava.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.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.i18n.CookieLocaleResolver;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;

@Configuration
public class AppConfig extends WebMvcConfigurerAdapter {
	@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.jeejava.controller;

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

@Controller
public class ViewController {
	@GetMapping("/")
	public String view() {
		return "view";
	}
}

Creating main class

Create below main class to startup the Spring Boot application. 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.jeejava.main;

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

@SpringBootApplication(scanBasePackages = "com.jeejava")
public class Application {
	public static void main(String[] args) {
		SpringApplication.run(Application.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-1.12.4.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.

When you see the default language – English

spring boot internationalization example

When you select the language – Bengali

spring boot internationalization example

When you select the language – Hindi

spring boot internationalization example

When you select the language – French

spring boot internationalization example

When you select the language – Dutch

spring boot internationalization example

You may also would like to read JSF 2 Internationalisation Example

Thanks for reading.

Tags:

I am a professional Web developer, Enterprise Application developer, Software Engineer and Blogger. Connect me on Roy Tutorials Twitter Facebook  Google Plus Linkedin Or Email Me

Leave a Reply

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