Search code examples
javaspring-bootinternationalizationlocale

MessageSource not using the same locale as Thymeleaf


I set user locale based on the session attribute.

@SpringBootApplication
@ServletComponentScan
@Configuration
public class Webapp {

    // Thymeleaf
    @Bean
    public LayoutDialect layoutDialect() {
    return new LayoutDialect();
    }

    @Bean
    public LocaleResolver localeResolver() {
    SessionLocaleResolver localeResolver = new SessionLocaleResolver();
    localeResolver.setLocaleAttributeName("user_locale"); // Not strictly needed
    localeResolver.setDefaultLocale(Locale.ENGLISH);
    return localeResolver;
    }

    @Bean
    public MessageSource messageSource() {
    ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
    messageSource.setBasename("classpath:lang/messages");
    messageSource.setDefaultEncoding("UTF-8");
    return messageSource;
    }


    public static void main(String[] args) {
        SpringApplication.run(Webapp.class, args);
    }
}

When I use Thymeleaf template, everything with #{..} gets translated via messages_XX.properties based on the correct language XX (which is specified in the session attribute). However, messageSource.getMessage(text, null, null) always returns English. How can I fix this? I do not even know where to start debugging.


Solution

  • To fix the issue you can retrieve the current locale from the LocaleContext associated with the current thread. For example in the controller like this:

        @GetMapping("/customers")
        public String showUserList(Model model) {
            Locale currentLocale = LocaleContextHolder.getLocale();
            log.info("Current locale: {}", currentLocale);
            model.addAttribute("customers", customerService.getCustomers());
            return "customers";
        }
    

    You can then pass the locale to the messageSource:

    messageSource.getMessage(text, null, currentLocale)