2013-08-19 120 views
1

这里是我的地区配置如何获取控制器中的当前语言?

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

当我尝试调用的语言环境中使用控制器

@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)。

+0

'lang = en'只是一个请求参数。使用'@ RequestParam'。 –

+0

是的,但如果没有这个请求参数,变量'lang'将不可用。 – misco

回答

3

您可以使用Spring为此提供的类LocaleContextHolder。从技术文档:

用作中央持有者当前区域在Spring,无论 必要的:例如,在MessageSourceAccessor。 DispatcherServlet 会在此处自动公开其当前区域设置。其他应用程序也可以将它们公开,以使像MessageSourceAccessor 这样的类自动使用该Locale。

然后在你的控制器只要致电:

LocaleContextHolder.getLocale(); 

检索使用Spring的语言环境。

LocaleContextHolder.getLocale() javadoc。

相关问题