基礎名_語言_國家.properties
基礎名_語言.properties
基礎名.properties
// 例
csdn_zh_CN.properties // 中國大陸簡體
csdn_en_US.properties // 美國英語
csdn.properties // 預設回退
中文屬性文件**必須**用 native2ascii 轉 Unicode 轉義:
native2ascii -encoding UTF-8 src.properties target.properties
<constant name="struts.custom.i18n.resources" value="csdn" />
<s:text name="welcome" />
<s:textfield name="realname" key="user" /> <!-- 表單標籤自動取 key -->
public class MyAction extends ActionSupport {
public String execute() {
String msg = getText("welcome"); // 簡單 key
String msg2 = getText("welcome", new String[]{"張三", "學習"}); // 含佔位符
}
}
資源文件:welcome={0},歡迎來到{1}
<s:text name="welcome">
<s:param><s:property value="realname"/></s:param>
<s:param>學習</s:param>
</s:text>
在 Java 包下放 package_zh_CN.properties,該包及子包 Action 自動訪問。**搜尋順序**:包級 → 全域常量指定資源。
Action 類同目錄下放 ActionClassName_zh_CN.properties。**搜尋順序**:Action 級 → 向上包級 → 全域。
<s:i18n name="csdn">
<s:text name="welcome"/>
</s:i18n>
<!-- 包路徑寫法 -->
<s:i18n name="cn/csdn/action/package">
<s:text name="welcome"><s:param>小張</s:param></s:text>
</s:i18n>
OGNL(Object-Graph Navigation Language)是 Struts2 默認表達式引擎,強於 EL:
user.getFullName()@java.lang.Math@PI、@com.Const@STATUS_OKActionContext (Map)
├── #application → ServletContext
├── #session → HttpSession
├── #request → HttpServletRequest 屬性
├── #parameters → Request 參數
├── #attr → page→request→session→application 順序查找
└── root (ValueStack / OgnlValueStack)
├── [0] Action 實例(棧頂)
├── [1] OgnlUtil 等內部對象
└── ...

username(從棧頂向下查找)。# 前綴 #session.userId、#request['key']。Struts2 用 StrutsRequestWrapper 包裝 HttpServletRequest,重寫 getAttribute(name):
public Object getAttribute(String name) {
Object val = super.getAttribute(name); // 先找 request 屬性
if (val == null && ActionContext.getContext() != null) {
val = ActionContext.getContext().getValueStack().findValue(name); // 再找 ValueStack
}
return val;
}
因此 JSP 中 ${username} 實際走的是 request.getAttribute("username"),被攔截轉向 ValueStack。
<!-- 建構 List -->
<s:set name="list" value="{'zhangming','xiaoi','liming'}" />
<s:iterator value="#list" var="n">
<s:property value="n"/><br/>
</s:iterator>
<!-- 建構 Map -->
<s:set name="foobar" value="#{'foo1':'bar1', 'foo2':'bar2'}" />
<s:iterator value="#foobar">
<s:property value="key"/>=<s:property value="value"/><br/>
</s:iterator>
<s:set> 的 scope 屬性可指定存放範圍(application/session/request/page/action),預存入 OGNL Context。