I18n in Spring boot + Thymeleaf

I am trying to create a multilingual application using Spring boot and Thymeleaf.

I made several properties files to save various messages, but I can only display them in my browser language (I tried extensions to change the browser language, but they don't seem to work), in any case I would like to put a button on my web site to fulfill this duty (change language), but I don’t know how and where to find how to manage it.

We collect our configuration for you:

Project structure

Project structure


configuration class I18n

import org.springframework.context.MessageSource; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.support.ResourceBundleMessageSource; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @Configuration @EnableWebMvc public class I18nConfiguration extends WebMvcConfigurerAdapter { @Bean public MessageSource messageSource() { ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource(); messageSource.setBasename("i18n/messages"); messageSource.setDefaultEncoding("UTF-8"); return messageSource; } } 

Thymleaf HTML Page

 <!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org" th:with="lang=${#locale.language}" th:lang="${lang}"> <head> <title>Spring Boot and Thymeleaf example</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> </head> <body> <h3>Spring Boot and Thymeleaf</h3> <p>Hello World!</p> <p th:text="${nombre}"></p> <h1 th:text="#{hello.world}">FooBar</h1> </body> </html> 

Messages (property files)

messages_en_US.properties

 hello.world = Hello people 

messages_es.properties

 hello.world = Hola gente 

Actually the message is displayed in Spanish, but I don’t know how to change it, so if you could help me a lot, thanks.

Another question that comes to my mind ... How to get messages from the database instead from the properties file?

+6
source share
1 answer

Your application should extend WebMvcConfigurerAdapter

 @SpringBootApplication public class NerveNetApplication extends WebMvcConfigurerAdapter { public static void main(String[] args) { SpringApplication.run(NerveNetApplication.class, args); } @Bean public LocaleResolver localeResolver() { return new CookieLocaleResolver(); } @Bean public LocaleChangeInterceptor localeChangeInterceptor() { LocaleChangeInterceptor lci = new LocaleChangeInterceptor(); lci.setParamName("lang"); return lci; } @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(localeChangeInterceptor()); } 

}

Then in the browser you can switch the language using the lang parameter Example: http: // localhost: 1111 /? Lang = kh , which messages_kh.properites will store the contents of the Khmer language.

+9
source

All Articles