如何在控制器中获取当前语言?

时间:2013-08-19 15:53:23

标签: java spring spring-mvc

这是我的语言环境配置

<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>

当我尝试使用

在控制器中调用locale时
@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());
    ...
}

它返回不同的值。但是当我使用URL ?lang=en中的GET参数在网站上切换语言时,它在所提到的控制器调用中没有任何改变。 i18n工作正常,它从正确的文件加载标签。但是我希望在我的控制器中获得更改的语言。我想在打开的页面上独立获取选择的语言(在URL中有/无请求参数lang)。

1 个答案:

答案 0 :(得分:4)

您可以使用Spring为此目的提供的LocaleContextHolder类。来自文档:

  

用作Spring中当前Locale的中心持有者,无论在哪里   必要的:例如,在MessageSourceAccessor中。 DispatcherServlet的   在此处自动公开其当前的Locale。其他应用可以   揭露它们,使像MessageSourceAccessor这样的类   自动使用该语言环境。

然后在你的控制器中打电话:

LocaleContextHolder.getLocale();

使用Spring检索语言环境。

LocaleContextHolder.getLocale() javadoc。