This is the structure of the Project:
Add some languages properties in src/main/resources/messages_****.properties. Spring default base name starts with 'messages'. You can find out the evidence from org.springframework.boot.autoconfigure.MessageSourceAutoConfiguration class. Add a couple of messages to each file, and we’ll use them to change the labels on our sample application's based on the client's locale.
/src/main/resources/messages_en_US.properties
user.name=Name
user.email=Email
/src/main/resources/messages_zh_CN.properties
user.name = \u59D3\u540D
user.email = \u7535\u5B50\u90AE\u4EF6
Let's Application class extends WebMvcConfigurerAdapter and configure a LocaleResolver.
@SpringBootApplication
public class Application extends WebMvcConfigurerAdapter{
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Bean
public LocaleResolver localeResolver() {
return new CookieLocaleResolver();
}
}
update view page like this.
<th th:text="#{user.name}">Name</th>
<th th:text="#{user.email}">Email</th>
Run Application class, you can get different locale based on your browser language.
If you want to set these messages properties into a foler in src/main/resources, please do a configuration in application.properties file.
spring.messages.basename=i18n/messages
spring.messages.encoding=UTF-8
If you want to get locale like this: http://localhost:8080/users?lang=en , please do below setting.
@SpringBootApplication
public class Application extends WebMvcConfigurerAdapter{
public static void main(String[] args) {
SpringApplication.run(Application.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());
}
}
Configure a LocaleChangeInterceptor. You can switch language with param lang.