1. 程式人生 > >struts2與freemarker國際化操作

struts2與freemarker國際化操作

struts2 自帶一個攔截器

<interceptor name="i18n" class="com.opensymphony.xwork2.interceptor.I18nInterceptor"/>

原始碼簡單分析下:

I18nInterceptor.CookieLocaleFinder localeFinder = new I18nInterceptor.CookieLocaleFinder(invocation);

通過這句話,跟蹤到下圖


通過跟蹤原始碼,找到CookieLocalFinder 繼承自  localfinder.

這裡是struts2設定語言key值的地方,查詢key值request_local在傳入的parameters 中是否存在。

如果存在request_local,就設定列舉型別storage值為session,也就是儲存方式。

如果request_local不存在,查詢request_only_local是否存在。

如果存在,就是none,就只設置這一次的訪問語言為xxx。

在I18nInterceptor中:

I18nInterceptor.CookieLocaleFinder localeFinder = new I18nInterceptor.CookieLocaleFinder(invocation);
Locale locale = this.getLocaleFromParam(localeFinder.getRequestedLocale());//設定key值 locale = this.storeLocale(invocation, locale, localeFinder.getStorage());//設定儲存方式,傳入上下文
this.saveLocale(invocation, locale);//儲存設定好的local local是一個bean型別,是儲存所有語言的。
invocation.getInvocationContext().setLocale(locale); //往下跟程式碼就是把local存入放入上下文。
這個是儲存的地方。有時間可以看下,struts2載入時,讀取的方式。
儲存的key值:
public static final String LOCALE = "com.opensymphony.xwork2.ActionContext.locale";

好了,原始碼到這,怎麼用才是最重要的~

首先編寫語言配置檔案:

我的idea匯入的maven專案,直接在resource目錄下,新增兩個檔案

globalMessage_en_US.properties    


 
struts2.cn.language=chinese
struts2.us.language=English
struts2.module=Module{0}

globalMessage_zh_CN.properties


 
struts2.cn.language=中文
struts2.us.language=英文
struts2.module=第{0}章

struts2需要一下配置,可以配置在struts2.properties或者struts2.xml

struts.i18n.reload=true //是否每次重新載入配置檔案
#struts.locale=zh_CN
struts.locale=en_US
struts.i18n.encoding=UTF-8
struts.custom.i18n.resources=globalMessage //資源的字首
或者struts2.xml:

 <constantname="struts.custom.i18n.resources"value="globalMessage"></constant>

    <constantname="struts.i18n.encoding"value="utf-8"/>

<constant name="struts.locale" value="en_US" />


啟動專案,就可以直接取到資源裡面配置的屬性了。

普通的jsp頁面引入struts2標籤以後,直接

<%@taglib uri="/struts-tags" prefix="s"%>
<@s.property value="%{getText('struts2.title')}" /> 可以取到值

freemarker結合的,需要這麼引入

<#assign s=JspTaglibs["/WEB-INF/struts-tags.tld"]> 取值一樣

然後就是更改中英文。老夫傳你個ajax,少年拿去用吧~

function changeLanguage(language){
 $.ajax({
    url: window.location.pathname,
    type:"POST",
    dataType: "json",
    async:false,
    data: {request_locale:language},
    success: function( data ) {
       window.location.reload();
    },
    error : function(){
       window.location.reload();
    }
 });
}
     globalMessage_ en_US.properties    傳入紅色部分就夠了

js取值一樣:

var ChooseFiles='<@s.property value="%{getText('struts2.ChooseFiles')}"/>';
注意,如果freemarker標籤改成[]  相應的 所有的地方都改成[]  而不是<>  

帶引數的

<@s.property value="%{getText('struts2.title',{'sad'})}" /> 可以取到值

   <@s.textname="login.title"/> 用name屬性來載入資原始檔的key值,

       <@s.textname="login.title">

              <@s.param>hello</@s.param>

              <@s.param>index</@s.param>

       </@s.text>

       或者:<@s.propertyvalue="%{getText('login.title',{'hello','index'})}"/>


愉快的學習到這裡就結束了~有問題留言吧~