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'})}"/>


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


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章