3

想,如果我沒有鑰匙在我的屬性的一個文件,我得到像一個例外:spring mvc i18n:如果key不在屬性文件中,如何設置默認語言環境?

javax.servlet.ServletException:javax.servlet.jsp.JspTagException:沒有下代碼「標籤中的信息。取消'locale'en'。

假設它不在我的messages_ch_CN.properties中有任何方式,如果它不在該文件中,它應該檢查messages_en_En文件。 或者是否有任何工作圍繞任何人實施。

回答

4

例如,你有:2語言

messages_ch_CN.properties /*in the property file lang=Chinese*/ 
messages_en_EN.properties /*in the property file lang=English*/ 
messages.properties /*in the property file lang=English default*/ 

messages.properties這是默認的屬性,它總是包含在整個應用程序使用的每個關鍵。

NAME-servlet.xml

<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns="http://www.springframework.org/schema/beans" 
     xmlns:context="http://www.springframework.org/schema/context" 
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
     xmlns:mvc="http://www.springframework.org/schema/mvc" 
     xsi:schemaLocation="http://www.springframework.org/schema/beans 
      http://www.springframework.org/schema/beans/spring-beans-3.2.xsd 
      http://www.springframework.org/schema/context 
      http://www.springframework.org/schema/context/spring-context-3.2.xsd 
      http://www.springframework.org/schema/mvc 
      http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd"> 

    <context:component-scan base-package="com.example.controller"/> 

    <mvc:annotation-driven/> 
    <mvc:resources mapping="/resources/**" location="/resources/"/> 

    <bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource"> 
     <property name="basename" value="classpath:com/example/i18n/messages"/> 
     <property name="fallbackToSystemLocale" value="false"/> 
     <property name="defaultEncoding" value="UTF-8"/> 
    </bean> 

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

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

</beans> 

<property name="fallbackToSystemLocale" value="false"/> - 說的是,如果你沒有財產messages_ch_CN.propertiesmessages_en_EN.properties或在這些財產的一個沒有必要的密鑰,例如:標題,春天將使用messages.properties默認爲

if <property name="fallbackToSystemLocale" value="true"/> - spring使用用戶本地化的部署環境,但它不好,因爲用戶的部署環境可能與我們提供的語言不同。如果用戶的語言環境與我們提供的語言不同,則彈簧使用messages.properties

+0

非常感謝...它工作正常 – Dineshkumar 2014-04-03 12:29:07

2

一個解決辦法是子類messageSource你使用(即ReloadableResourceBundleMessageSource),並覆蓋它的resolveCode()使:

  • 它看起來對於指定的代碼和語言環境的信息(通過調用super.resolveCode(code, locale))。
  • 如果它找不到它,那麼它會查找一個默認語言環境(通過調用super.resolveCode(code, defaultLocale))。

然後使用新創建的類作爲messageSource

+0

謝謝你會嘗試 – 2012-02-27 10:59:22

+0

請參閱http://stackoverflow.com/a/18156149/470749關於如何做到這一點的實際例子。 – Ryan 2013-08-09 21:48:18

0

始終提供默認messages文件(不含locale規範),該文件始終包含應用程序中使用的每個密鑰。如果沒有繼承其中一個ResourceBundle實現,則無法自動查找另一個locale

相關問題