I am new to using Spring and Thymeleaf and I can't figure out where to put my localization .properties files. I have this Bean:
@Bean
public MessageSource messageSource() {
ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
messageSource.setBasenames("classpath:messages/messages", "classpath:messages/validation");
// if true, the key of the message will be displayed if the key is not
// found, instead of throwing a NoSuchMessageException
messageSource.setUseCodeAsDefaultMessage(false);
messageSource.setDefaultEncoding("UTF-8");
// # -1 : never reload, 0 always reload
messageSource.setCacheSeconds(0);
return messageSource;
}
Inside login.html:
<p th:text="#{messages.hello}">Welcome to our site!</p>
Inside messages_en.properties
:
messages.hello=Apparently messages work
My project structure:
I have tried creating a folder inside WEB-INF called messages but apparently I am not getting something right. Any ideas?
Edit: Updated question with code relevant to mesages.
I know this one is old. But I have looked for a solution and got to this post.
I have found a solution by myself and others with the same problem might get here.
So this is how I solved it:
Inject MessageSource
into SpringTemplateEngineBean
.
@Bean
public SpringTemplateEngine templateEngine(MessageSource messageSource, ServletContextTemplateResolver templateResolver) {
SpringTemplateEngine engine = new SpringTemplateEngine();
engine.setTemplateResolver(templateResolver);
engine.setMessageSource(messageSource);
return engine;
}
Now Thymeleaf knows about your MessageSource
and evaluates your expressions.
Basename in this XML means prefix of .properties
files that contain different translations.
Let's say that you need two languages: English (en
) and Polish (pl
).
All you need to do is to set your Basename
to messages
like this:
messageSource.setBasename("classpath:messages");
and then put two files messages_en
and messages_pl
in your classpath
(WEB-INF
should suffice, although consider using src/main/resources
directory).
This is a basic example that should be easily adapted to your case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With