I am using Spring 3.1 and want to find the locale active for the current user is there a way to grab the locale directly without being forced to pass it from the controller
I was also looking for how to access the locale without passing the Locale
around, but I'm still pretty new to Spring and found most solutions to be confusing. It turns out, though, that Spring MVC does store the locale in thread local storage. It can be accessed by:
Locale locale = LocaleContextHolder.getLocale();
The last approach [...] is based on a thread local in order to provide the current locale in any entity of your architecture. [...] You must be aware that the content of the LocaleContextHolder corresponds by default to the locale specified within the Web request.
From: Configuring locale switching with Spring MVC 3. (That post also offers alternative configurations/methods for getting the locale, which might be useful for anyone looking to do this).
You can also view the LocaleContextHolder
docs from Spring here.
We had the same need, so came up with putting Locale
into ThreadLocal
context. We already had an object (some user information) stored in ThreadLocal
context, so just appended it (looks like a hack, but the quickest solution we found).
It depends on where you have configured to store the locale, in session or in cookie?
In my application I have configured to store the user locale in its session with below mentioned configuration.
<mvc:interceptors>
<ref bean="localeChangeInterceptor"/>
</mvc:interceptors>
<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.SessionLocaleResolver">
<property name="defaultLocale" value="en"/>
</bean>
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basenames">
<list>
<value>/WEB-INF/i18n/labels</value>
<value>/WEB-INF/i18n/messages</value>
<value>/WEB-INF/i18n/include</value>
</list>
</property>
<property name="defaultEncoding" value="UTF-8"/>
</bean>
If you have done somthing like this then you can easily retrieve the locale parameter from the session.
Hope this helps you.
Cheers.