在 Struts 1.0 時代,一個 Action 類僅能對應一個 execute 方法,處理單一業務。若需在同一模組實現增刪改查等多個操作,常見做法是在表單隱藏字段 operAt 中傳遞操作類型,在 execute 中用 if-else 判斷分發:
String operAt = myForm.getOperat();
if ("create".equals(operAt)) { ... }
else if ("save".equals(operAt)) { ... }
這導致 Action 類膨脹、邏輯混雜、難以維護。
DispatchAction 允許在一個 Action 類中定義多個業務方法,方法簽名與 execute 一致:
public ActionForward create(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception { ... }
public ActionForward save(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception { ... }
關鍵在於 <action> 元素的 parameter 屬性指定請求參數名(如 method):
<action path="/telConsle"
type="com.example.TelAction"
name="telForm"
scope="request"
validate="false"
parameter="method" />
https://host/app/telConsle.do?method=save<input type="hidden" name="method" value="">,按鈕 onclick 設值提交。建議:使用標準 HTML <input> 而非 <html:hidden>,避免 FormBean 需額外定義 getter/setter,且靜態標籤不受 Struts 標籤庫版本影響。
DispatchAction 將相關業務邏輯聚合在單一 Action 類中,配合 parameter 屬性實現方法級分發,大幅減少樣板代碼,提升可讀性與維護性。是 Struts 1.x 時代處理 CRUD 聚合的最佳實踐之一。