Sunday, August 23, 2020

Spring Boot - Internationalization working example

 

Add Internationalization in Spring Boot App

 



import java.util.Locale; 

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

import org.springframework.context.annotation.Bean;

import org.springframework.context.support.ResourceBundleMessageSource;

import org.springframework.web.servlet.LocaleResolver;

import org.springframework.web.servlet.i18n.SessionLocaleResolver;

 

@SpringBootApplication

public class RestfulServicesApplication {

 

       public static void main(String[] args) {

              SpringApplication.run(RestfulServicesApplication.class, args);

       }

      

         //Add these two methods for i18n

       @Bean

       public LocaleResolver localeResolver() {

       SessionLocaleResolver localeResolver= new SessionLocaleResolver();

       localeResolver.setDefaultLocale(Locale.US);

       return localeResolver;

       }

      

      

       public ResourceBundleMessageSource messageSource() {

          ResourceBundleMessageSource messageSource= new ResourceBundleMessageSource();

          //message referes to the property file name without extention

          messageSource.setBasename("messages");

          return messageSource;

            

       }

}

 

 

 //Rest Controller class

@RestController

public class HelloWorldController {

 

       @Autowired

       MessageSource messageSource;

      


       @GetMapping(path = "/hello-world-i18n")public String 

         helloWorld(@RequestHeader(name="Accept-Language",required=false) Locale locale) {

             String msg=messageSource.getMessage("my.app.message",null, locale);

             return msg;

       }

      

 

}

 

//Define properties files

messages.properties

 

my.app.message="Hello"

 

messages_fr.properties

 

my.app.message=" Bonjour"

 

 

Call Rest API with Accept-Language Header :

 

Get : http://127.0.0.1:8080/hello-world-i18n

Header:

Accept-Language : fr

Bonjour

 

Get : http://127.0.0.1:8080/hello-world-i18n

Header:

Accept-Language : en

Hello

 

 

 

 

 

 

 

 

No comments:

Post a Comment

Create a Digital Clock using HTML and JavaScript

Create a Digital Clock using HTML and JavaScript  <! DOCTYPE html> < html > < head > ...

Followers

Search This Blog

Popular Posts