SpringMVC+Freemarker+jQuery實現多語言(國際化)切換
一、spring啟動配置檔案修改
其中<value>message/messages</value>指定的properties資原始檔名,
檔案在src/main/resources根目錄的message資料夾下
<!-- 資原始檔繫結器 --> <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource"> <property name="basenames"> <list> <value>message/messages</value> </list> </property> </bean> <!-- 國際化操作 攔截器 必需配置,可以和其它國際化方式通用 --> <bean id="localeChangeInterceptor" class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"/> <!-- 基於Session的國際化配置 --> <bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver"> </bean>
二、新增依賴檔案
如果是使用eclipse開發環境的
找到maven包spring-webmvc-4.2.6.RELEASE.jar路徑下的spring.ftl檔案
如果是使用IDEA開發環境的
找到Maven:org.springframework:spring-webmvc:4.2.6.RELEASE下面的spring.ftl檔案
把該檔案拷貝放在頁面的檔案根目錄下
三、新增資原始檔
新增資原始檔messages.properties, messages_en_US.properties, messages_zh_CN.properties,
如需要支援多種國際化語言,只需新增對應的資原始檔,
messages.properties配置檔案作用是當找不到其他有關帶有messages的檔案時預設讀取這個配置檔案的資訊
注意路徑和上面配置的一致,在classpath的src/main/resources根目錄的message資料夾下:
其中Resource Bundle 'messages'是IDEA自動生成的,不用理會,知道三個檔案都在message目錄下就可以
Messages.properties配置檔案作用是當找不到其他有關帶有messages的檔案時預設讀取這個配置檔案的資訊
messages_en_US.properties是英文的配置檔案
messages_zh_CN.properties為中文的配置檔案,字串需為ASCII編碼
中文與英文的配置檔案當中的鍵位必須一致,切換時才能讀取到該鍵位資訊,如果配置當中沒有該鍵位名稱,而頁面上卻填寫了,進入該頁面上時會報錯顯示不了
配置檔案中的鍵位名稱可以根據自己專案的需求去定
四、資料庫選單列表修改
由於選單列表是從資料庫表當中獲取資料顯示,所以資料庫當中添加了一張英文選單列表,一張中文選單列表
當前端頁面切換語言的時候,後端把查詢語句修改成獲取對應的選單就行了
五、後端程式碼修改
在獲取語言選單進行重定向進入主頁面時,獲取的是什麼語言的選單列表,Locale的值就設定什麼樣的語言
前兩句程式碼是Locale設定語言,Locale locale = new Locale("en", "US")該程式碼設定為英文
Locale locale = new Locale("en", "US");
request.getSession().setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME, locale);
response.sendRedirect("/index/home");
在controller控制層注入MessageSource類,該類實現國際化i18n,找到對應的資原始檔
@Autowired
private MessageSource messageSource;
String userManagement = messageSource.getMessage("user.userManagement", null, locale);
其中像user.userManagement這些為資原始檔中的鍵位
六、前端頁面
可以在web頁面的頭部.ftl檔案中引入spring.ftl檔案,這個根據自己的專案去操作,頁面佈局一般頭部為所有頁面共用部分
<#import "spring.ftl" as spring/>
寫上js程式碼切換時使用ajax請求傳送到後端進行切換配置檔案和呼叫不同的資料庫選單表
<script type="text/javascript">
$(function() {
$(document).delegate(".language", "click", function() {
$(this).addClass("active").siblings().removeClass("active");
var html = $(this).find('a').html();
$("#language").html(html);
var data = $(this).find('input').val();
$.ajax({
type : "POST",
data : {
"new_lang" : data
},
url : "/index/changeLanguage",
dataType : "json",
success : function(json) {
window.location.reload();
}
})
});
});
</script>
頁面上需要切換顯示中英文的地方改成配置檔案中的鍵位,例如以下寫法:
<@spring.message "language"/>
如頁面上的標籤內的姓名,原寫法:
<label for="userName" class="col-sm-2 control-label">姓名</label>
全部修改為:
<label for="userName" class="col-sm-2 control-label"><@spring.message "user.userName"/></label>
user.userName是資原始檔中的鍵位,每個鍵位必須唯一
中文配置檔案與英文配置檔案的鍵位必須一致