Spring, thimeleaf and localized strings

I'm new to using Spring and Thymeleaf, and I can't figure out where to put the .properties localization 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:

structure

I tried to create a folder inside WEB-INF called messages, but apparently I do not understand what is correct. Any ideas?

Edit: Updated question with message related code.

+6
source share
3 answers

I know that he is old. But I was looking for a solution and got this post.

I found the solution myself, while others with the same problem can get it here. So this is how I solved it:

Introduce MessageSource into SpringTemplateEngineBean.

 @Bean public SpringTemplateEngine templateEngine(MessageSource messageSource, ServletContextTemplateResolver templateResolver) { SpringTemplateEngine engine = new SpringTemplateEngine(); engine.setTemplateResolver(templateResolver); engine.setMessageSource(messageSource); return engine; } 

Now Thimeleaf knows about your MessageSource and evaluates your expressions.

+6
source

The base name in this XML stands for the prefix of .properties that contain different translations.

Let's say that you need two languages: English ( en ) and Polish ( pl ). All you have to do is set Basename to messages as follows:

 messageSource.setBasename("classpath:messages"); 

and then put the two messages_en and messages_pl files in your classpath ( WEB-INF should be enough, although consider using the src/main/resources directory).

This is a basic example that should be easily adapted to your case.

+3
source

You must expose the Thymeleaf SpringTemplateEngine as a bean so that Spring MessageSource your MessageSource into it:

 @Bean public SpringTemplateEngine templateEngine() { final SpringTemplateEngine templateEngine = new SpringTemplateEngine(); templateEngine.setTemplateResolver(templateResolver()); return templateEngine; } 

For MessageSource configuration MessageSource see MichaΕ‚ Rybak's answer .

+3
source

All Articles