【问题标题】:Controller HttpServletRequest locale does not change控制器 HttpServletRequest 区域设置不会更改
【发布时间】:2017-09-25 19:41:37
【问题描述】:

当我通过请求参数更改首选语言时,网页中的语言会发生变化(使用<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 的语言环境没有改变?

【问题讨论】:

    标签: java spring controller request locale


    【解决方案1】:

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

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

    或者只是从静态持有者那里获取语言环境: LocaleContextHolder.getLocale()

    【讨论】:

    • 一方面HttpServletRequest.getLocale() 的意外行为,另一方面未能阅读该方法究竟做了什么。感谢您的回答。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多