之前一直看見 i18N ,如今才知道原來 i18N 就是 Internationalization,由於以 i 開頭,以 N 結尾,共18個字母,也就是國際化的意思。在百度搜索主頁上沒有看見中英文的切換,畢竟百度在中國是爲了中國人而設計的,不必弄個英文的切換。google搜索主頁上是有的,由於谷歌在中國的服務器放到了香港,因此還有繁體切換。這是怎麼作到的呢?其實原理很簡單,用Struts2很容易實現的。以實現中英文切換爲例作一下說明:java
第一步:在src目錄下添加兩個資源文件,命名方式很重要的。格式:baseName_language_country.properties。還有兩種命名方式,均可以的,這個不用過多研究。好比,實現中英文切換咱們要添加 resource_zh_CN.properties 和 resource_en_US.properties。而後將各個key-value對添加到這兩個文件中,key字段必定要統一。如:服務器
其中,value值能夠使用佔位符,好比:你好{0},至於怎麼傳參數,稍後再解釋。app
第二步:配置struts.properties文件,這個文件也是放在src目錄下的。jsp
第一個鍵值對是爲了告訴程序,國際化資源文件是loginResource開頭命名的資源文件。post
到這裏其實配置就算完事兒了,接下來就是在各個地方使用。google
(1)在jsp中使用。舉兩個例子。url
<s:text name="login.title"></s:text>spa
<s:textfield name="username" key="login.username"></s:textfield>設計
還能夠輸出帶佔位符的信息。如,有一個 login.welcome = 你好{0},那麼能夠用下面這種方式來顯示:code
<s:text name="login.welcome"><s:param><s:property value="username"/></s:param></s:text>
(2)在Action中使用。舉個例子:
getText("login.username");
還能夠使用帶佔位符的信息。如,有一個 login.welcome = 你好{0},那麼能夠用下面這種方式來顯示:
String params[] = {"張三"};
String welcome = getText("login.welcome", params);
第三步,實如今jsp頁面中的中英文切換。
index.jsp中主要部分代碼以下:
1 <a href="lang.action?request_locale=zh_CN">中文</a> 2 <a href="lang.action?request_locale=en_US">English</a> 3 4 <s:form id="loginform" action="login" method="post"> 5 <s:textfield name="username" key="login.username"></s:textfield> 6 <s:textfield name="psd" key="login.psd" ></s:textfield> 7 <s:submit key="login.submit"></s:submit> 8 </s:form>
主要看前兩行代碼,lang.action其實就是一個實現頁面轉換的Action,沒有什麼實質性的內容,隨便定義一個HelloAction.java,在execute()方法中返回個success就好了。url中的這個參數 request_locale會被 i18n 攔截器讀取,而後根據這個值設置語言環境。 i18n 攔截器是struts中default裏面自帶的攔截器。
struts.xml配置以下:
1 <action name="login" class="com.main.action.LoginAction"> 2 <exception-mapping result="error" exception="java.lang.RuntimeException"></exception-mapping> 3 <result name="success">/success.jsp</result> 4 <result name="error">/index.jsp</result> 5 <result name="input">/index.jsp</result> 6 <result name="regist">/regist.jsp</result> 7 </action> 8 9 <action name="lang" class="com.main.action.HelloAction"> 10 <result name="success">/index.jsp</result> 11 </action>
哦了,基本完成了,接下來就是看效果啦。運行一下: