Search code examples
javaspringspring-mvctagslocale

Spring MVC: Difference between spring:message and request locale


I'm having some inconsistency and I need some expert advice. I'm using Spring MVC 3.2

Having this beans:

<bean id="messageSource"
  class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
    <property name="basename" value="classpath:messages" />
    <property name="defaultEncoding" value="UTF-8"/>
    <property name="cacheSeconds" value="10" /> <!-- for easier development -->
</bean>

<bean id="localeChangeInterceptor"
  class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
    <property name="paramName" value="lang" />
</bean>

<bean id="localeResolver"
  class="org.springframework.web.servlet.i18n.CookieLocaleResolver">
    <property name="defaultLocale" value="en"/>
</bean>

And two diferent message files:

messages.properties
messages_es.properties

When using spring tag the locale resolves to "es" and uses messages_es as expected (it's my system lang).

However, if I try to get the locale programatically I always get "en". I've tried this options:

Option 1:

@Autowired
private LocaleResolver localeResolver;
....
localeResolver.resolveLocale(request);

Option 2:

LocaleContextHolder.getLocale();

Option 3:

RequestContextUtils.getLocale(request);

All of them result with "en" lang.

The question is, How do I get the locale used by spring:message tag ??

Acording to documentation,

When a request comes in, the DispatcherServlet looks for a locale resolver, and if it finds one it tries to use it to set the locale. Using the RequestContext.getLocale() method, you can always retrieve the locale that was resolved by the locale resolver.

But all my texts in the final html are in "es" and this method returns "en"


Solution

  • Well, I'll answer myself. I debugged it deep enought to find out that the problem was a missing property in ReloadableResourceBundleMessageSource definition. Adding fallbackToSystemLocale = false and removing default locale in localeResolver now locale resolves to "es" in requests.

    So far so good. Sadly the part of changing locale via "?lang=en" parameter doesn't work but thats another story.

    Resolution:

    <bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <property name="basename" value="classpath:messages" />
        <property name="defaultEncoding" value="UTF-8"/>
        <property name="cacheSeconds" value="2" />
        <property name="fallbackToSystemLocale" value="false" />
    </bean>
    
    <bean id="localeChangeInterceptor" class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
        <property name="paramName" value="lang" />
    </bean>
    
    <bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver" />
    

    and

    LocaleContextHolder.getLocale();