I am trying to get i18n to work with my spring boot application, which uses thymeleaf as template engine.
I followed some tutorials, which showed me how to define message source and locale resolver, so I made this configuration class:
@Configuration
@EnableWebMvc
public class AppConfig extends WebMvcConfigurerAdapter {
@Bean
public MessageSource messageSource() {
ReloadableResourceBundleMessageSource msgSrc = new ReloadableResourceBundleMessageSource();
msgSrc.setBasename("i18n/messages");
msgSrc.setDefaultEncoding("UTF-8");
return msgSrc;
}
@Bean
public LocaleResolver localeResolver() {
CookieLocaleResolver resolver = new CookieLocaleResolver();
resolver.setDefaultLocale(new Locale("en"));
resolver.setCookieName("myI18N_cookie");
return resolver;
}
@Override
public void addInterceptors(InterceptorRegistry reg) {
LocaleChangeInterceptor interceptor = new LocaleChangeInterceptor();
interceptor.setParamName("locale");
reg.addInterceptor(interceptor);
}
}
Then, in my resource folder (src/main/resources) i made folder i18n and inside i put messages.properties and messages_sl.properties
inside there is defined first.greeting = Hello World!
And this is my thymeleaf template:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" th:with="lang=${#locale.language}" th:lang="${lang}">
<head>
<meta charset="UTF-8"/>
</head>
<body>
<a href="/?locale=en">English</a> | <a href="/?locale=sl">Slovenian</a>
<h3 th:text="#{first.greeting}"></h3>
</body>
</html>
My Controller is nothing special, it just forwards this view when I access it and in my properties file i have defined:
spring.thymeleaf.mode=LEGACYHTML5
spring.thymeleaf.cache=false
However, when I load page, instead of Hello World! I get ??first.greeting_en?? or ??first.greeting_sl??, depending on set locale.
Everywhere I looked I saw same configuration, so I am really lost as what am I missing.
And here is my project structure:
🗁 src
└─── 🗁 main
├─── 🗁 java
│ └─── 🗁 com
│ └─── 🗁 mjamsek
│ └─── 🗁 Simple_i18n
│ ├─── 🗁 conf
│ └─── 🗁 controller
└─── 🗁 resources
├─── 🗁 i18n
│ ├─── messages.properties
│ └─── messages_sl.properties
├─── 🗁 static
└─── 🗁 templates
Add the classpath:
prefix to MessageSource's
basename
msgSrc.setBasename("classpath:i18n/messages");