java - Spring MVC : Difference between spring:message and request locale

标签 java spring spring-mvc tags locale

我有一些不一致的地方,我需要一些专家的建议。我正在使用 Spring MVC 3.2

有了这个 bean :

<bean id="messageSource"
  class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
    <property name="basename" value="classpath:messages" />
    <property name="defaultEncoding" value="UTF-8"/>
    <property name="cacheSeconds" value="10" /> <!-- for easier development -->
</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>

以及两个不同的消息文件:

messages.properties
messages_es.properties

当使用 spring 标签时,区域设置解析为“es”并按预期使用 messages_es (这是我的系统语言)。

但是,如果我尝试以编程方式获取语言环境,我总是得到“en”。我尝试过以下选项:

选项 1:

@Autowired
private LocaleResolver localeResolver;
....
localeResolver.resolveLocale(request);

选项 2:

LocaleContextHolder.getLocale();

选项 3:

RequestContextUtils.getLocale(request);

所有结果都是“en”lang。

问题是,如何获取 spring:message 标记使用的语言环境?

根据文档,

When a request comes in, the DispatcherServlet looks for a locale resolver, and if it finds one it tries to use it to set the locale. Using the RequestContext.getLocale() method, you can always retrieve the locale that was resolved by the locale resolver.

但是我在最终 html 中的所有文本都是“es”,并且此方法返回“en”

最佳答案

好吧,我自己来回答。我对其进行了足够深入的调试,发现问题是 ReloadableResourceBundleMessageSource 定义中缺少属性。添加fallbackToSystemLocale = false并删除localeResolver中的默认区域设置现在区域设置解析为请求中的“es”。

到目前为止一切顺利。遗憾的是,通过“?lang=en”参数更改区域设置的部分不起作用,但那是另一个故事了。

分辨率:

<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
    <property name="basename" value="classpath:messages" />
    <property name="defaultEncoding" value="UTF-8"/>
    <property name="cacheSeconds" value="2" />
    <property name="fallbackToSystemLocale" value="false" />
</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" />

LocaleContextHolder.getLocale();

关于java - Spring MVC : Difference between spring:message and request locale,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18832619/

相关文章:

java - 如何在将一个页面导航到另一页面时发布 CODENAMEONE 表单(包括其所有组件)?

java - 在 Eclipse 中打开项目

java - Spring - 创建 Bean 时出现奇怪的错误

java - 连接错误的用户时出错

JavaFX 图形 "blurred"或消除锯齿? (没有使用效果)

java - 当 DateTextField 隐藏时,如何隐藏 DatePicker 图标?

java - 上下文初始化失败 - Alfresco

spring - 我应该在 Spring 项目中包含系统测试吗?

java - 当页面不存在时,未在未经授权的 URL 上找到页面 404

javascript - spring mvc hibernate Restful(并发)问题