【问题标题】:Spring does not using sources in default localeSpring 不使用默认语言环境中的源
【发布时间】:2013-09-22 16:19:10
【问题描述】:

我在 spring 配置中更改了默认语言环境,但是 spring 总是使用 messages_en.properties 而不是 messages.properties。似乎 Spring 忽略了我选择的语言环境。

定义的定位:

messages.properties
messages_en.properties

弹簧配置: application-context.xml

<bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver">
  <property name="defaultLocale" value="cs"/>
</bean>

<bean id="localeChangeInterceptor" class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
    <property name="paramName" value="lang" />
</bean>

<bean name="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
  <property name="basenames">
    <list>
      <value>messages</value>
    </list>
  </property>
  <property name="defaultEncoding" value="UTF-8" /> 
</bean>

servlet-context.xml

<mvc:interceptors>
 <mvc:interceptor>
  <mvc:mapping path="/**" />
  <exclude-mapping path="/admin/**"/>
  <exclude-mapping path="/image/**"/>
  <exclude-mapping path="/ajax/**"/>
  <beans:bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor" />
 </mvc:interceptor>
</mvc:interceptors>

在 JSP 页面中

<spring:message code="csn.terminology.csnId" />
<p>Current Locale : ${pageContext.response.locale}</p> 
<!-- output is 'cs', but messages are from messages_en.properties file --> 

项目中使用Spring Framework 3.2.4 提前感谢您的帮助。

【问题讨论】:

标签: java spring spring-mvc


【解决方案1】:

如果它是完整的配置,那么您忘记添加区域设置解析器 您可以像这样添加 SessionLocaleResolver 并设置默认语言环境属性

<bean id="localeResolver"
        class="org.springframework.web.servlet.i18n.SessionLocaleResolver">
        <property name="defaultLocale" value="en"></property>
    </bean>

【讨论】:

  • 那么对于这个 ResourceBundleMessageSource 只有一个解释,它有一个名为 setFallbackToSystemLocale link 的属性,默认为 true,因此如果您的 locale cs 的语言环境文件不包含消息对于代码,则使用您的系统区域设置。
【解决方案2】:

当 locale 为 null 时,AbstractMessageSource 调用 Locale.getDefault()

所以你应该设置默认语言环境如下:

   @Bean
   public MessageSource messageSource() {
      ResourceBundleMessageSource messageSource=new ResourceBundleMessageSource();
      messageSource.setBasename("messages");
      // SET DEFAULT LOCALE AS WELL
      Locale.setDefault(Locale.US);
      return messageSource;
   }

【讨论】:

  • 嗨 Elie,这可能不是理想的解决方案,因为您将使用 Locale.setDefault(Locale.US); (docs.oracle.com/javase/7/docs/api/java/util/…) 设置 JVM 的默认语言环境,这可能会在更大的应用程序中产生很多不良后果跨度>
猜你喜欢
  • 1970-01-01
  • 2020-04-05
  • 2014-03-31
  • 2018-06-13
  • 1970-01-01
  • 2012-01-21
  • 2017-08-05
  • 2016-07-13
  • 1970-01-01
相关资源
最近更新 更多