How to obtain the current language in a controller?
java, spring, spring-mvc
Solution
You can use `LocaleContextHolder` class that Spring provides for this purpose. From documentation:
Used as a central holder for the current Locale in Spring, wherever necessary: for example, in MessageSourceAccessor. DispatcherServlet automatically exposes its current Locale here. Other applications can expose theirs too, to make classes like MessageSourceAccessor automatically use that Locale.
Then in your controller just call:
LocaleContextHolder.getLocale();
to retrieve the locale using Spring.
LocaleContextHolder.getLocale() javadoc.
Problem
Here is my locale configuration ``` <bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource"> <property name="basename" value="classpath:messages" /> <property name="defaultEncoding" value="UTF-8" /> </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> <bean id="handlerMapping" class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"> <property name="interceptors"> <ref bean="localeChangeInterceptor" /> </property> </bean> ``` When I try to call locale in a controller using ``` @RequestMapping(value = "customers/customer-{idCustomer:[0-9]+}/detail", method = RequestMethod.GET) public ModelAndView detail(Map<String, Object> map, @PathVariable Integer idCustomer, Locale locale) { logger.info(locale.toString()); logger.info(request.getLocale().toString()); ... } ``` It returns different values. But when I switch a language on a site using GET param in URL `?lang=en`, it change nothing in mentioned controller's calls. i18n works fine, it loads a labels from correct file. But I want to obtain changed language in my controllers. I want to obtain choosed language independently on opened page (with/without request param `lang` in URL).