This is a quick blog post on how to add locale support for your REST API's using spring-boot. In this example you will learn to send localized content based on the Accept-Language header.
Accept-Language: Language Tag
eg:
* Send an API request with Accept-Language: en , you will get English language content.
* end an API request with Accept-Language: zh , you will get Chinese language (mandarin) content.
You can check the supported language tags from here.
https://www.oracle.com/java/technologies/javase/jdk8-jre8-suported-locales.html
Assume that your back-end needs to send localized contents based on the language choose from the front end application.
The easiest way is to keep this localized messages in a Resource bundle for each language. You can do this by using the ResourceBundleMessageSource.
Create a new resource bundle in src/main/resources directory. This directory holds the property files for each language. I have created a resource bundle named as menu and it contains 2 property files for both English and Chines (Mandarin) languages. A property file contain a key and value pairs. Key will be the message code and value is the actual message. You can add any no of language files as per your requirement. Let's take a look at the property files.
menu.propertiesNow we need to create a bean class to set these files to a ResourceBundleMessageSource.
We are all set, now we just need a Translator class to translate the message to specific language when the message code is given. We can write a simple class as below.
Comments
Post a Comment