深入解析 Struts 2 <action> 元素的動態配置能力:通配符映射 Action 名稱/類別/方法、驗證檔案命名規則、URL 匹配優先序、多種 Result 類型與動態結果資源決定機制。
name、class、method 參數化<action name="*Action" class="com.unmi.LoginRegistAction" method="{1}">
URL registAction.action → 執行 LoginRegistAction.regist()。
<action name="*_*" class="actions.{1}Action" method="{2}">
URL Book_save.action → 執行 actions.BookAction.save()。
語法說明:{1}、{2} 對應 name 中 * 依序匹配(同正則分組),{0} 為完整 name 值。得益於 Struts 2 每請求建立新 Action 實例,Struts 1 無法預載所有通配符實例。
<action name="*">
<result>/{1}.jsp</result>
</action>
搜尋順序:
<ActionClassName>-<ActionAliasName>-validation.xml(ActionAliasName 為 name 屬性值)<ActionClassName>-validation.xml同時存在時規則疊加/覆蓋。例:<action name="*Action" class="com.unmi.LoginRegistAction" method="{1}">,URL registAction.action 會搜尋:
LoginRegistAction-registAction-validation.xmlLoginRegistAction-validation.xml若定義 name="*"、name="*Action"、name="LoginAction":
LoginAction.action → 完全匹配 LoginActionabcAction.action → 按定義順序匹配第一個(*),而非匹配度最高(*Action)<default-action-ref>URL 無匹配 Action 時使用,配置於 <package> 內。
<result>(<action> 內)vs 全域 <global-results>name="success"、type="dispatcher"(JSP 轉發)type="plaintext"顯示頁面原始碼,中文易亂碼,用 <param name="charSet">GBK</param> 修正。
dispatcher vs redirect| dispatcher(轉發) | redirect(重導向) | |
|---|---|---|
| 請求參數/屬性 | 保留 | 丟失 |
| 地址欄 | 不變 | 改變(新請求) |
redirect-action:重導向至另一 Action參數:actionName、namespace。簡寫:<result type="redirect-action">actionName</result>。等同 Struts 1 <forward redirect="true">/anotherAction.do</forward>。亦可用 redirect 寫同等形式。
<action name="crud_*" class="com.unmi.CrudAction" method="{1}">
<result>/{1}.jsp</result>
</action>
URL crud_delete.action 成功 → 轉向 delete.jsp。
<action name="..." class="com.unmi.ShowAction">
<result>/show${user.type}</result>
</action>
Action 設定 ${user.type}="admin" → 轉向 showadmin.jsp。
<result>/<global-results> 完全對應 Struts 1 <forward>/<global-forwards>。