Spring – How to obtain a current user locale from Spring without passing it as a parameter to functions


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 to the service layer … etc.

does spring store the locale in a thread local storage where it can be grabbed by calling some static method?

Best Solution

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.

Related Question