1. Create in WEB-INF folder a new folder messages and add to this folder some files with a base name and suffix(without suffix is the default file).
2. Add to these files, key-value records like:
facebook.displayName=English Facebook -> messages.properties
facebook.displayName=China Facebook -> messages_zh_CN.properties
*You can also add other suffixes like fr for French
3. Now, i think it's time for some Java Config:)
@Configuration
@EnableWebMvc
public class WebMvcConfig extends WebMvcConfigurerAdapter {
@Bean
public LocaleChangeInterceptor localeChangeInterceptor(){
LocaleChangeInterceptor localeChangeInterceptor=new LocaleChangeInterceptor();
localeChangeInterceptor.setParamName("language");
return localeChangeInterceptor;
}
@Bean(name = "localeResolver")
public LocaleResolver sessionLocaleResolver(){
SessionLocaleResolver localeResolver=new SessionLocaleResolver();
localeResolver.setDefaultLocale(new Locale("en"));
return localeResolver;
}
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(localeChangeInterceptor());
}
@Bean
public MessageSource messageSource() {
ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
messageSource.setBasename("/WEB-INF/messages/messages");
return messageSource;
}
//...
}
* Note that "SessionLocalResolver" has a name. I don't know why, but declaring this without a name caused me some problems
* "language" will be the parameter that will have to be in request url for getting values from a different file
**language=fr will load values from messages_fr
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<title>Spring Security Example </title>
</head>
<body>
<p th:text="#{facebook.displayName}">Welcome to our grocery store!</p>
</body>
</html>
Because we have only two files, we have only 2 choises:
*call without paramater will result:



Very informative post
ReplyDeleteVery helpful. You have explained well using java config for internalization.
ReplyDeleteIf you are handling localization projects, my recommendation is to try a software localization tool like https://poeditor.com/
ReplyDelete