Struts2 <s:i18n>標籤示例

Struts2 <s:i18n>標籤是用來從聲明的資源包獲得消息, 不只是使用當前操作相關聯的資源包。看下麵一個完整的<s:i18n>標籤的例子:

1. 動作

Action類轉發請求。

I18nTagAction.java

package com.xuhuhu.common.action;

import com.opensymphony.xwork2.ActionSupport;

public class I18nTagAction extends ActionSupport{

	public String execute() throws Exception {

		return SUCCESS;
	}
}

2. 屬性檔

兩個屬性檔作為演示。

I18nTagAction.properties

i18n.msg = "This is a message from I18nTagAction.properties"

Custom.properties

i18n.msg = "This is a message from Custom.properties"

3. <s:i18n>標籤示例

下麵顯示<s:i18n>標籤的使用。

i18n.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
</head>

<body>
<h1>Struts2 <s:i18n>標籤示例 - www.xuhuhu.com</h1>

<h2>1.Get message from I18nTagAction.properties</h2>
Output :
<s:text name="i18n.msg" />

<h2>2.Get message from Custom.properties</h2>
Output :
<s:i18n name="com/zaixian/common/action/Custom">
	<s:text name="i18n.msg" />
</s:i18n>

</body>
</html>

它是如何工作的?

1.在示例1中,它會得到來自資源包的消息(I18nTagAction.properties)這是關想當前的操作類 (I18nTagAction.java)

2.在例2中,它會從“Custom.properties”屬性的檔得到消息,這個檔放在 com/zaixian/common/action/ 檔

不要放 .properties 尾碼
一個常見的錯誤,在國際化的標籤,如果聲明屬性名為.properties尾碼的檔,在Struts2將未能從聲明的資源包獲得消息。
錯誤的方式:
<s:i18n name="com/zaixian/common/action/Custom.properties">
	<s:text name="i18n.msg" />
</s:i18n>

正確的方式 :

聲明的屬性檔沒有 .properties 尾碼。
<s:i18n name="com/zaixian/common/action/Custom">
	<s:text name="i18n.msg" />
</s:i18n>

4. struts.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
 	<constant name="struts.devMode" value="true" />
	<package name="default" namespace="/" extends="struts-default">

		<action name="i18nTagAction"
			class="com.xuhuhu.common.action.I18nTagAction" >
			<result name="success">pages/i18n.jsp</result>
		</action>

	</package>
</struts>

5. 示例

http://localhost:8080/struts2i18ntag/i18nTagAction.action

在流覽器中打開上面的URL,顯示結果如下:

參考

  1. Struts2 <s:i18n>標籤文檔
下載代碼 - http://pan.baidu.com/s/1c0mHDlA



上一篇: Struts2 <s:include>標籤示例 下一篇: Struts2 <s:param>標籤示例