1. 程式人生 > >SpringMVC國際化支持

SpringMVC國際化支持

資源文件 number 通過 ssp 區域 utf-8 odin 路徑和 asd

這周公司領導希望我對一個項目,出一個國際化的解決方案,研究兩個小時,采用了SpringMVC的國際化支持,在此記錄下。

原理: 在DispatchServlet中註冊localeResolver(區域解析器),並添加Locale攔截器(LocaleChangeInterceptor),來檢測請求中的參數和語言環境的改變。

   在應用上下文中註冊ResourceBundleMessageSource,定義國際化文件在程序中的路徑和名稱。

  

1. 語言解析器

  在SpringMVC中,常用的語言解析器有

  Header resolver:通過解析客戶端請求頭信息中心的accept-language,來獲取用戶需要的國際化語言。詳見=AcceptHeaderLocaleResolver

  Cookie resolver:通過解析客戶端上Cookie指定的locale,來獲取用戶需要的國際化信息。詳見=CookieLocaleResolver

  Session resolver:通過解析客戶端請求域中的loacle信息,來獲取需要的國際化信息,並存儲在httpSession中。詳見=SessionLocaleResolver

    

技術分享圖片
1 <bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver">
2       <property name="defaultLocale" value="en_US" />
3
</bean>
View Code

2. 區域攔截器

  我們需要在DispatchServlet中註冊監控區域改變的攔截器, 他能幫助我們檢測請求參數,根據請求參數對應的語言,更改語言環境。

  

技術分享圖片
1 <mvc:interceptors>
2     <bean class="com.xxx.web.interceptor.IhgLocaleChangeInterceptor" />
3 </mvc:interceptors>
View Code

3. 國際化資源配置

      

技術分享圖片
1 <bean id="messageSource" class
="org.springframework.context.support.ResourceBundleMessageSource"> 2 <property name="defaultEncoding" value="UTF-8" /> 3 <property name="basename" value="classpath*:/ApplicationMessage" /> 4 <property name="useCodeAsDefaultMessage" value="true" /> 5 </bean>
View Code

4. 頁面國際化

  在這裏,我是用的是jstl的fmt標簽來實現國際化。有興趣的同學也可以使用spring的message標簽。

  1) 引入標簽庫<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>

  2) 指定國際化文件資源名<fmt:setBundle basename="ApplicationMessage" />

  3) 通過國際化資源文件的key,讀取文件信息。 <fmt:message key="security.account.number" />

5. 我們在第二步中選擇的是SessionResolver解析器。所以在請求中,我們需要在url的參數後面拼接上locale=具體語言標識(例如:locale=zh_CN)。

 註意:在每個頁面都拼接url的話會顯得麻煩,通常用戶會希望能做的,一次選擇語言後,之後都首選這種語言。所以有興趣的同學可考慮,通過擴展LocaleChangeInterceptor,來達到更完善的功能。

SpringMVC國際化支持