This tutorial will show you how to internationalize your Spring MVC application. It starts with the basics of internationalization, and then moves on to more advanced topics like how to use resource bundles, message formatters, and locale-specific templates.
Spring MVC Internationalization Tutorial is a tutorial that will teach you how to internationalize your Spring Boot application.
Internationalization (i18n) is the process of making your software or service capable of providing content in many languages. We’ll look at how the Spring-Boot framework handles internationalization in this lesson.
Overview
Because the internet has gone global, any application or website may now reach millions of people all over the globe. Despite the fact that half of the world’s population has internet access today, just approximately a quarter of internet users are English speakers. This implies that software developers must provide material in several languages in order to grow into new areas.
Internationalization is a fundamental need for most applications, and it can be accomplished quickly and easily using Spring Boot. Through the usage of Spring Interceptor, Resolver of Locationss, and Resource Bundles for various locales, Spring Boot offers enhanced support for Internationalization (i18n). This post will teach you how to use Spring Boot to accomplish internationalization.
Preparation:
I’ll be utilizing the following tools in this example:
- JDK 1.8
- Intellij Concept
- Maven
- Version 2.5.5 of the Springboot application
The following is the post’s structure:
In addition, the following is the blog’s growth plan:
- Make a web application using Spring Boot
- Dependencies should be included.
- Beans for configuration creation
- Make a controller bean
- Properties that are multilingual
- Create a View.
- Application Execution
Create a Spring Boot web application in the first step.
We begin by building a basic Spring Boot web application. To build an initial project template, go to the Spring Initializr website. We’ll use a project with the following information in this lesson.
We’ll create two sub-packages within our main package ‘com.appsdeveloperblog.springbooti18n’ after importing the project into the IDE:
- The file ‘InternationalController.java’ contains the class ‘InternationalController.java’.
- Class ‘InternationalizationConfig‘ with filename ‘InternationalizationConfig.java‘ is included in this configuration.
The ultimate structure of the project will be as follows:
In the following part, we’ll go through the config and controller classes in more depth.
Step 2: Take into account your responsibilities.
Then, in our application, we must add the following dependencies:
The following is the “pom.xml” source code:
spring-boot-i18n 4.0.0 com.appsdeveloperblog jar appsdeveloperblog-spring-boot-i18n 0.0.1-SNAPSHOT org.springframework.boot.i18n org.springframework.boot.i18n org.springframework.boot.i18n spring-boot-starter-parent org.springframework.boot 2.5.0 UTF-8 UTF-8 1.8 org.springframework.boot spring-boot-starter-thymeleaf org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-thymeleaf org.springframework.boot spring-boot-maven-plugin
Create a Configuration Bean in the third step.
LocaleResolver is used by Spring MVC to retrieve the locale associated with web requests, and this locale object is then used to choose suitable language messages. It first needs a LocaleResolver bean. We’ll go through this in more depth below:
Locale Resolver
Spring provides a variety of LocaleResolverTypes, but the most popular ones are shown below:
Type | Explanation |
---|---|
AcceptHeaderLocaleResolver | This just picks Locale from the client web browser’s Accept-Language header. |
CookieLocaleResolver | Cookies are used to get information about the location. Locale information is saved in a cookie via the setLocale() function. Resolved locale data is saved as long as cookies are active in this case. |
SessionLocaleResolver | Obtain information about the session’s locale. The setLocale() method saves the session’s Locale information. Resolved localization data is saved in a single HTTP session in this case. |
FixedLocaleResolver | It is necessary to utilize a fixed locale. There is no setLocale() function. |
The standard package “org.springframework.web.servlet.i18n” has a number of additional locale resolvers. Please see the following official link for additional information: org.springframework.web.servlet.i18n.
Let’s take a closer look at the CookieLocaleResolver and SessionLocaleResolver locale types:
CookieLocaleResolver
If you utilize a locale object depending on the user’s PC or browser settings, you won’t be able to alter it if the client wishes to see the website in a different language. As a result, another alternative is to adjust the locale using cookies, as seen below. We may now set the locale in the cookies depending on the user’s preferences. The following is an example of CookieLocaleResolver code for establishing locales:
public @Bean locale CookieLocaleResolver CookieLocaleResolver locale Resolver() locale = new CookieLocaleResolver(); resolver = new CookieLocaleResolver(); Locale.US; Resolver.setDefaultLocale(Locale.US); locale = Resolver.setCookieName(“locale”); locale.setCookieMaxAge(60 * 60); resolver.setCookieMaxAge(60 * 60); return localeResolver; resolver.setCookiePath(“/”);
SessionLocaleResolver
SessionLocaleResolver is recommended if a user wishes to adjust the locale for each each HTTP session:
public @Bean LocaleResolver is a location resolver. SessionLocaleResolver locale Resolver() localeResolver.setDefaultLocale(Locale.US); return localeResolver; resolver = new SessionLocaleResolver(); resolver = new SessionLocaleResolver(); resolver = new SessionLocaleResolver(); resolver = new SessionLocaleResolver
For the sake of simplicity, we’ll call ourselves “SessionLocaleResolver.”
Interceptor
Second, we need another bean in our class for interceptor.
The LocaleChangeInterceptor is used to update the new Locale depending on the value of a request’s language argument. This is needed when a large number of people contact our spring application from various locations.
To make this work, we must include the LocaleChangeInterceptor in the registry interceptor of the application. Override the addInterceptors function in the configuration class, which should extend the WebMvcConfigurer class.
public LocaleChangeInterceptor localeChangeInterceptor() @Bean @Bean @Bean @Bean @Bean @Bean @Bean @Bean @Bean @Bean @Bean @Bean @Bean @Bean @Bean @ if localeChangeInterceptor = new LocaleChangeInterceptor(); if localeChangeInterceptor.setParamName(“lang”); if localeChangeInterceptor.setParamName(“lang”); if localeChangeInterceptor.setParamName(“lang”); if localeChangeInterceptor.setParamName(“lang”); if registry.addInterceptor(localeChangeInterceptor()); @Override public void addInterceptors(InterceptorRegistry registry)
The following is the whole source code for the configuration class “InternationalizationConfig.java”:
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.LocaleResolver; import org.springframework.web.servlet.config.annotation; import org.springframework.web.servlet.config.annotation; import org.springframework.web.servlet.config.annotation; import org. Import org.springframework.web.servlet.config.annotation from InterceptorRegistry. Import org.springframework.web.servlet.config.annotation into WebMvcConfigurer. @Configuration public class import org.springframework.web.servlet.i18n.LocaleChangeInterceptor; import org.springframework.web.servlet.i18n.SessionLocaleResolver; import java.util.Locale; @Configuration public class import org.springframework.web.servlet.i18n.LocaleChangeInterceptor; import java.util.Local WebMvcConfigurer is used by InternationalizationConfig. public LocaleResolver localeResolver @Bean () localeResolver.setDefaultLocale(Locale.US); return localeResolver; SessionLocaleResolver localeResolver = new SessionLocaleResolver(); LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor(); localeChangeInterceptor.setParamName(“lang”); return localeChangeInterceptor; @Bean public LocaleChangeInterceptor localeChangeInterceptor() registry.addInterceptor(localeChangeInterceptor()); @Override public void addInterceptors(InterceptorRegistry registry)
Create a controller in step four.
The controller will then be used to fulfill our welcome page request. The following is the full source code for “InternationalController.java”:
import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation; package com.appsdeveloperblog.springbooti18n.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.ui.Model; import org.springframework. Import org.springframework.web.bind.annotation for RequestMapping. @Controller public class; RequestMethod InternationalController @RequestMapping(value = “/welcome”, method= RequestMethod.GET) public String welcome() return “welcome”; @RequestMapping(value = “/welcome”, method= RequestMethod.GET) public String welcome() return “welcome”; public String home(Model model) return “redirect:welcome”; @RequestMapping(“/”) public String home(Model model) return “redirect:welcome”;
Multilingual Properties Files (Step 5)
The language files serve as the foundation for an internationalized program. We generate multi-language message files in Spring-Boot, such as messages:
- properties,
- messages es.properties,
- messages en.properties is an example of a property file.
The language code is followed by the file’s base name (messages). In addition, if we want to be more precise, the country code may be used. The key and value pairs are stored in each file. Using this resource, you can identify all of the texts that are available in several languages.
It’s important to remember that the key for the same text in all files must be the same.
As an example,
Hello!!!!!!!!!!! (message en.properties) hello = hello!!!!!! (message fr.properties) Hallo!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! hello =!!!!!!! (message nl.properties) (message jp.properties)
These files must be under “src/main/resources” by default. We generated two language files in our example: English and French message properties files.
The messages fr.properties file for the French language will be as follows –
Hello and welcome to appsdeveloperblog.com. This is an excellent place to learn. language.change=Translate from one language to another. french=francais, english=english, english=english, english=english, english=english, english=english, english
messages.properties and messages en.properties will be set to the default language –
Hello from appsdeveloperblog.com, welcome.message= It’s an excellent learning environment. language.change=Change the language to: language.english=English language.french=French language.change=Change the language to: language.english=English language.french=French
Step 6: Create a View
To show internationalization messages in Thymeleaf, just include the message key, such as this #key, inside a Thymeleaf tag; the most frequent place to do this is in th:text since it is the most popular place to display text, but it may also be used in other tags, such as th:value.
Within the project’s resources/templates directory, we’ll build a website.
The source code for “welcome.html” may be found here.
:
Step 7: Launching the Program
Now we can start the Spring Boot application by creating the main class:
@SpringBootApplication public class SpringBootI18nApplication public static void main(String[] args) SpringApplication.run(SpringBootI18nApplication.class, args); import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication
Finally, we’ll launch our program by typing the following command or using the IDE’s ‘Run’ button. The application launched on Tomcat port 8080, as you can see.
spring-boot:run mvn
Go to your browser and type in the following URL after the program has begun.
http://localhost:8080/
It will take you to the welcome page you made in step 6.
Following that, the page is automatically updated with the chosen language depending on the language selected from the dropdown.
The French page, for example, is as follows:
Exceptions to the Rule for Locale Messages
We may also utilize Spring Boot Internationalization’s support to deliver local exception or information messages in this case.
We may specify our error or informative messages in the files messages.properties and other locale-specific files. Spring Boot will choose appropriate locale messages and build the error message itself depending on available locales when the program detects an error.
messages en.properties, for example.
Invalid inbound message payload.” innboundrequest.200=”Invalid inbound message payload.” innboundrequest.201=”Unknown inbound message attribute 0″ innboundrequest.201=”Unknown inbound message attribute 0″ innboundrequest.201=”Unknown in “Unknown attribute value 0 for Request ID 1.” innboundrequest.202=”Unknown attribute value 0 for Request ID 1.” “Inbound message missing,” says innboundrequest.203.
messages fr.properties
innboundrequest.200=”Donnu00E9es utiles de message entrant non valides” innboundrequest.200=”Donnu00E9es utiles de message entrant non valides” innboundrequest.201=”Attribut 0 de message entrant inconnu” innboundrequest.201=”Attribut 0 de message entrant inconnu” innboundrequest.201=”Attribu innboundrequest.202=”Valeur d’attribut inconnue 0 for l’ID de demande 1″ innboundrequest.202=”Valeur d’attribut inconnue 0 pour l’ID de demande 1″ innboundrequest.203=”Message entrant manquant” innboundrequest.203=”Message entrant manquant” innboundrequest.203
Conclusion
In general, if your application serves a wide range of customers all over the globe, it’s critical that it responds appropriately depending on the nation and language. We learnt how Spring-Boot offers out-of-the-box support for internalization in this article. For worldwide users, this makes our applications more intuitive and comprehensible.
Good luck with your studies!
Spring MVC internationalization is a process of using different language strings in your application. This tutorial will teach you how to do that with the help of an example. Reference: spring:message example.
Related Tags
- messagesource in spring mvc
- spring mvc multi language example
- spring messagesource
- spring boot internationalization rest api
- sessionlocaleresolver