Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 250
ams Avatar asked May 29 '12 02:05

ams


People also ask

How do you apply localization in Spring application?

Getting Started with Spring i18n: Preparing Your View Templates. The first step towards a localized application is to extract all static text from your templates into a localization file. Later, this is used to look up the required text bits according to the selected language.

What is the default locale resolver used in Spring framework?

Interface LocaleResolver The default implementation is AcceptHeaderLocaleResolver , simply using the request's locale provided by the respective HTTP header.

What is locale resolver?

LocaleResolverThe LocaleResolver interface has implementations that determine the current locale based on the session, cookies, the Accept-Language header, or a fixed value. In our example, we have used the session based resolver SessionLocaleResolver and set a default locale with value US.


1 Answers

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.

like image 93
Sam Routledge Avatar answered Sep 30 '22 16:09

Sam Routledge