Revan
Revan

Reputation: 119

Spring default locale not working as I expected for CookieLocaleResolver

I have two files for the text I want to translate:

messages_es_ES.properties messages_en_US.properties

I'm using a CookieLocaleResolver:

@Bean
public LocaleResolver localeResolver() {
    CookieLocaleResolver cookieLocaleResolver = new CookieLocaleResolver();
    cookieLocaleResolver.setCookieName("language");
    cookieLocaleResolver.setCookieMaxAge(3600);
    cookieLocaleResolver.setDefaultLocale(new Locale("es_ES"));
    return cookieLocaleResolver;
}

And this LocaleChangeInterceptor:

@Bean
public LocaleChangeInterceptor localeChangeInterceptor() {        
    LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor();
    localeChangeInterceptor.setParamName("language");
    return localeChangeInterceptor;
}

@Override
public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(localeChangeInterceptor());
}

In my jsp, I use this links:

<a href="?language=en_US">EN</a> 
<a href="?language=es_ES">ES</a>

Everything works, and the language is correctly changed when I click on one link, but everything is shown in English (in the system locale, to be more specific) when I start the application, even if I set "es_ES" as the default locale.

Upvotes: 4

Views: 2955

Answers (2)

Elie Nehm&#233;
Elie Nehm&#233;

Reputation: 239

You can set default locale as follow:

   @Bean
   public MessageSource messageSource() {
      ResourceBundleMessageSource messageSource=new ResourceBundleMessageSource();
      messageSource.setBasename("messages");
      // SET DEFAULT LOCALE AS WELL
      Locale.setDefault(Locale.US);
      return messageSource;
   }

When locale is null, AbstractMessageSource calls Locale.getDefault()

Upvotes: 1

Revan
Revan

Reputation: 119

Solved, I changed the property setFallbackToSystemLocale from the ResourceBundleMessageSource to false, as mentioned by @noobandy here. Now everything is working as expected.

Upvotes: 3

Related Questions