控制器HttpServletRequest语言环境不会更改

时间:2017-09-25 19:41:37

标签: java spring controller request locale

当我通过请求参数更改优先语言时,语言 会更改网页 (使用<spring:message code="xxxx"/>检索邮件),但区域设置 在控制器中不会更改 ,例如:

private void simpleControllerMethod(HttpServletRequest request, HttpServletResponse response, ModelAndView model) {
        System.out.println(request.getLocale().toString()); // prints default application locale no matter what
    }

dispather-servlet.xml包含:

<bean id="messageSource"
    class="org.springframework.context.support.ResourceBundleMessageSource">
    <property name="basename">
        <value>messages</value>
    </property>
    <property name="defaultEncoding" value="UTF-8" />
    <property name="fallbackToSystemLocale" value="false" />
</bean>

<bean id="localeResolver"
    class="org.springframework.web.servlet.i18n.CookieLocaleResolver">
    <property name="defaultLocale" value="lt" />
    <property name="cookieName" value="lang" />
    <property name="cookieMaxAge" value="3600"/>
</bean>

<mvc:interceptors>  
    <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
          <property name="paramName" value="lang"></property>
    </bean>
</mvc:interceptors>

为什么HttpServletRequest的语言环境不会改变?

1 个答案:

答案 0 :(得分:2)

HttpServletRequest.getLocale()不会为您提供当前的语言环境。它为您提供了首选(浏览器首选 - 从标题中判断)。 如果要获取当前区域设置,则必须通过方法参数传递区域设置:

private void simpleControllerMethod(HttpServletRequest request, HttpServletResponse response, ModelAndView model,Locale locale) {
    System.out.println(locale);
}