天天看點

SpringMVC 實作國際化

注意:文章是在SpringMVC架構已經存在的基礎上介紹添加國際化示例
1. 添加國際化資源檔案

資源檔案放到配置檔案能夠找到的位置即可,在這裡放在WEB-INF/lang 目錄下,如下圖所示。

SpringMVC 實作國際化
2. 修改Spring配置檔案

在Spring配置檔案springmvc-servlet.xml(或其他)中添加以下代碼

<bean id="defaultAnnotationHandlerMapping"  class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
  <property name="interceptors">
    <list>
        <!-- 配置多語言改變的攔截器 -->
        <ref bean="localeChangeInterceptor" />
    </list>
  </property>
</bean>

<!-- 國際化資源檔案綁定器 -->
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
    <property name="basenames">
        <list>
            <value>/WEB-INF/lang/M_Messages</value>
            <value>/WEB-INF/lang/M_Errors</value>
            <value>/WEB-INF/lang/M_Pages</value>
        </list>
    </property>

    <!-- 預設為false,找不到messageKey的話,就抛出NoSuchMessageException --> 
    <!-- 把它設定為True,則找不到不會抛出異常,而是使用messageKey作為傳回值。 -->
    <property name="useCodeAsDefaultMessage" value="false" />

    <!-- 設定編碼類型,注意:message相關的properties檔案在建立的時候,-->
    <!-- 需要時utf-8類型, 而且網站編碼也是utf-8類型,否則可能中文亂碼 -->
    <property name="defaultEncoding" value="UTF-8" />
</bean>

    <!-- 可以使用LocaleChangeInterceptor修改本地化資訊。 -->
    <!-- 這個攔截器需要被添加到處理器映射中。 它可以偵測請求中某個特定的參數, -->
    <!-- 然後調用上下文中的LocaleResolver中的 setLocale()方法,相應地修改本地化資訊。 -->
<bean id="localeChangeInterceptor"           class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
    <property name="paramName" value="siteLang" />
</bean>

    <!-- SessionLocaleResolver允許從使用者請求相關的session中擷取本地化資訊。 -->
<bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver" >
     <property name="defaultLocale" value="zh_CN"></property>
</bean>
           
3. 頁面操作
1. 在jsp頂部引入<%@taglib uri="http://www.springframework.org/tags" prefix="spring" %>
 2. 在需要顯示的标簽出使用:< spring:message code=‘username’/>來代替該标簽,
     帶參數的使用方式:< spring:message code=‘username’arguments="2017,你好"/>
           
4. 測試使用
浏覽器通路:

 - http://localhost:8910/lang/login.html?siteLang=en_US (英文)
 - http://localhost:8910/lang/login.html?siteLang=zh_CN (中文簡體)
           

通路不同連結顯示的不同效果

SpringMVC 實作國際化

繼續閱讀