I'm trying to make a multilanguage application using Spring boot and Thymeleaf.
I made few properties files to save the different messages but I'm only able to display it in my browser language (I tried extensions to change browser locale but they seem to not be working), anyway I wanted to put a button in my website to do this duty (changing the language), but I don't know how or where to find how to manage this.
Gonna show you my config:
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;
}
}
<!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_en_US.properties
hello.world = Hello people
messages_es.properties
hello.world = Hola gente
Actually the message is displaying in Spanish, not sure how would I change this, so if you could help me thank you very much.
There's another question that comes to my mind... How would I get the messages from the Database instead from the properties file?
Your application should extends 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 on browser you can switch language with param lang Example: http://localhost:1111/?lang=kh which messages_kh.properites will store the content of Khmer language.