[英]Controller HttpServletRequest locale does not change
When I change preferred language via request parameter the language changes in the web pages (messages are retrieved with <spring:message code="xxxx"/>
) but locale does not change in the controllers, for example:当我通过请求参数更改首选语言时,网页中的语言会发生变化(使用
<spring:message code="xxxx"/>
检索<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 contains: 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>
Why locale does not change for HttpServletRequest?为什么 HttpServletRequest 的语言环境不会改变?
HttpServletRequest.getLocale() doesn't give you current locale. HttpServletRequest.getLocale() 不给你当前的语言环境。 It gives you the preferred (preferred by the browser -judging from the header).
它为您提供首选(浏览器首选 - 从标题判断)。 If you want to get current locale you have to pass the Locale through method parameter:
如果要获取当前语言环境,则必须通过方法参数传递语言环境:
private void simpleControllerMethod(HttpServletRequest request, HttpServletResponse response, ModelAndView model,Locale locale) {
System.out.println(locale);
}
or just get Locale from static holder: LocaleContextHolder.getLocale()或者只是从静态持有者获取 Locale:LocaleContextHolder.getLocale()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.