溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

使用Struts2怎么實(shí)現(xiàn)國(guó)際化

發(fā)布時(shí)間:2021-04-15 17:31:31 來(lái)源:億速云 閱讀:172 作者:Leah 欄目:編程語(yǔ)言

今天就跟大家聊聊有關(guān)使用Struts2怎么實(shí)現(xiàn)國(guó)際化,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結(jié)了以下內(nèi)容,希望大家根據(jù)這篇文章可以有所收獲。

第一步:在src目錄下添加兩個(gè)資源文件,命名方式很重要的。格式:baseName_language_country.properties。還有兩種命名方式,都可以的,這個(gè)不用過(guò)多研究。比如,實(shí)現(xiàn)中英文切換我們要添加 resource_zh_CN.properties 和 resource_en_US.properties。然后將各個(gè)key-value對(duì)添加到這兩個(gè)文件中,key字段一定要統(tǒng)一。如:

使用Struts2怎么實(shí)現(xiàn)國(guó)際化 

使用Struts2怎么實(shí)現(xiàn)國(guó)際化     

其中,value值可以使用占位符,比如:你好{0},至于怎么傳參數(shù),稍后再解釋。

第二步:配置struts.properties文件,這個(gè)文件也是放在src目錄下的。

使用Struts2怎么實(shí)現(xiàn)國(guó)際化

第一個(gè)鍵值對(duì)是為了告訴程序,國(guó)際化資源文件是loginResource開(kāi)頭命名的資源文件。

到這里其實(shí)配置就算完事兒了,接下來(lái)就是在各個(gè)地方使用。

(1)在jsp中使用。舉兩個(gè)例子。

<s:text name="login.title"></s:text>
<s:textfield name="username" key="login.username"></s:textfield>

還可以輸出帶占位符的信息。如,有一個(gè) login.welcome = 你好{0},那么可以用下面這種方式來(lái)顯示:

<s:text name="login.welcome"><s:param><s:property value="username"/></s:param></s:text>

(2)在Action中使用。舉個(gè)例子:

getText("login.username");

還可以使用帶占位符的信息。如,有一個(gè) login.welcome = 你好{0},那么可以用下面這種方式來(lái)顯示:

String params[] = {"張三"};

String welcome = getText("login.welcome", params);

第三步,實(shí)現(xiàn)在jsp頁(yè)面中的中英文切換。

index.jsp中主要部分代碼如下:

<a href="lang.action?request_locale=zh_CN" rel="external nofollow" >中文</a>
   <a href="lang.action?request_locale=en_US" rel="external nofollow" >English</a>
   
   <s:form id="loginform" action="login" method="post">
     <s:textfield name="username" key="login.username"></s:textfield>
     <s:textfield name="psd" key="login.psd" ></s:textfield>
     <s:submit key="login.submit"></s:submit>
   </s:form>

主要看前兩行代碼,lang.action其實(shí)就是一個(gè)實(shí)現(xiàn)頁(yè)面轉(zhuǎn)換的Action,沒(méi)有什么實(shí)質(zhì)性的內(nèi)容,隨便定義一個(gè)HelloAction.java,在execute()方法中返回個(gè)success就行了。url中的這個(gè)參數(shù) request_locale會(huì)被 i18n 攔截器讀取,然后根據(jù)這個(gè)值設(shè)置語(yǔ)言環(huán)境。 i18n 攔截器是struts中default里面自帶的攔截器。

struts.xml配置如下:

<action name="login" class="com.main.action.LoginAction">
      <exception-mapping result="error" exception="java.lang.RuntimeException"></exception-mapping>
      <result name="success">/success.jsp</result>
      <result name="error">/index.jsp</result>
      <result name="input">/index.jsp</result>
      <result name="regist">/regist.jsp</result>  
    </action>
    
    <action name="lang" class="com.main.action.HelloAction">
      <result name="success">/index.jsp</result>
    </action>

看完上述內(nèi)容,你們對(duì)使用Struts2怎么實(shí)現(xiàn)國(guó)際化有進(jìn)一步的了解嗎?如果還想了解更多知識(shí)或者相關(guān)內(nèi)容,請(qǐng)關(guān)注億速云行業(yè)資訊頻道,感謝大家的支持。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI