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?
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.
Interface LocaleResolver The default implementation is AcceptHeaderLocaleResolver , simply using the request's locale provided by the respective HTTP header.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With