Spring MVC 學習(十一)國際化(i18n)處理與配置
國際化概述
1)預設情況下,SpringMVC根據Accept-Language參數判斷用戶端的本地化類型。
2)當接受到請求時,SpringMVC會在上下文中查找一個本地化解析器(LocalResolver),找到後使用它擷取請求所對應的本地化類型資訊。
3)SpringMVC還允許裝配一個動态更改本地化類型的攔截器,這樣通過指定一個請求參數就可以控制單個請求的本地化類型。
SessionLocaleResolver&LocaleChangeInterceptor工作原理

本地化解析器和本地化攔截器:
AcceptHeaderLocaleResolver:根據HTTP請求頭的Accept-Language參數确定本地化類型,如果沒有顯式定義本地化解析器,SpringMVC使用該解析器。
CookieLocaleResolver:根據指定的Cookie值确定本地化類型
SessionLocaleResolver:根據Session中特定的屬性确定本地化類型
LocaleChangeInterceptor:從請求參數中擷取本次請求對應的本地化類型。
要使用的jar包有 jstl.jar 和 standard.jar
下面簡單實作國際化中文的轉換:
1)首先,準備兩個資源檔案,分别展示英文和中文:首先,準備兩個資源檔案,這兩個資源檔案放在項目的src目錄下,分别展示英文和中文:
i18n_en_US.properties
i18n_en_CN.properties
2)在spring MVC 的配置檔案中加載國際化資源
<!-- springmvc 國際化 -->
<!-- 配置國際化資源檔案 -->
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basenames" value="i18n"/>
</bean>
<!-- 配置 SessionLocaleResolver id 必須為localeResolver-->
<bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver"></bean>
<!-- 配置 LocaleChangeInterceptor -->
<mvc:interceptors>
<bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"></bean>
</mvc:interceptors>
3)建立個簡單頁面來測試國際化
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<a href="locale?locale=zh_CN">國際中文</a><br/>
<a href="locale?locale=en_US">國際英語</a>
</body>
</html>
4)開發處理請求的Controller
public class TestOtherController {
@RequestMapping("locale")
public String getlocal() {
return "success";
}
}
5)請求結果跳轉到那個success.jsp ,擷取結果
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@ taglib prefix="f" uri="http://java.sun.com/jsp/jstl/fmt" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Insert title here</title>
</head>
<body>
<f:message key="i18n.username"></f:message>
<f:message key="i18n.password"></f:message>
</body>
</html>
6)啟動TOMACT ,測試結果如下:
點選,轉換中文: