Struts 1.x 作為 MVC Model 2 經典框架風靡多年,但隨著 Web 發展暴露出代碼量大、類爆炸、單元測試難、Servlet API 耦合等痛點。Struts 2 (源自 WebWork 2.2 + Struts Ti 合併) 從架構層面徹底重設計,本文從 Action 模型、IoC、攔截器、全維度特性表 深度對比,助你評估遷移價值。
| 維度 | Struts 1.x | Struts 2 |
|---|---|---|
| 基類/介面 | 必須繼承 org.apache.struts.action.Action (抽象類) | POJO,無需繼承/實現任何介面 (慣例繼承 ActionSupport) |
| 表單數據封裝 | 獨立 ActionForm (FormBean) | 直接在 Action 屬性上 (Getter/Setter) |
| 返回類型 | ActionForward | String (邏輯視圖名),或實現 Action 介面用常量 |
| 執行方法 | 固定 execute(mapping, form, req, res) | 任意 public String xxx(),配置指定 |
| 參數獲取 | 方法參數傳遞 HttpServletRequest/Response | IoC 依賴注入 (Setter 注入、介面注入、構造器注入) |
| 線程模型 | 單例 Action,需手動同步屬性 | 每請求一實例,天然線程安全 |
public class ActionForStruts2 extends ActionSupport {
private String message;
public String getMessage() { return message; }
@Override
public String execute() {
message = "Hello from Struts2. Now: " + new Date();
return SUCCESS; // 常量 "success"
}
}
Struts 2 內建輕量級 IoC 容器 (源自 WebWork),並推薦整合 Spring 統一管理依賴。
public class IoCForStruts2 implements ServletRequestAware {
private HttpServletRequest request;
public void setServletRequest(HttpServletRequest request) { this.request = request; }
public String execute() {
// 直接使用 request 物件
return Action.SUCCESS;
}
}
關鍵點:Struts 2 每請求創建新 Action 實例,屬性天然線程安全,無需擔心單例併發問題。
Struts 1.x 無內建攔截器 (需第三方 SAIF);Struts 2 以攔截器鏈為核心,國際化、類型轉換、驗證、文件上傳、事務管理等全部建構於攔截器之上。

ServletDispatcher。intercept(ActionInvocation invocation)。invocation.invoke() 前後執行邏輯,或直接返回結果短路。params:參數注入 (OGNL 表達式賦值 Action 屬性)conversionError:類型轉換錯誤處理validation:驗證框架整合workflow:驗證失敗返回 INPUT 結果fileUpload:文件上傳支援i18n:國際化語言切換timer:性能監控
public class MyInterceptor extends AbstractInterceptor {
@Override public String intercept(ActionInvocation invocation) throws Exception {
System.out.println("Before action");
String result = invocation.invoke();
System.out.println("After action: " + result);
return result;
}
}
配置:<interceptor name="my" class="com.example.MyInterceptor"/> 並加入攔截器棧。
| 特性 | Struts 1.x | Struts 2 |
|---|---|---|
| Action 類型 | 繼承抽象類 | POJO + 可選介面 |
| 線程模型 | 單例,需同步 | 每請求一實例,無同步煩惱 |
| Servlet 依賴 | 強耦合 (execute 參數) | 無耦合 (Map 封裝),可選注入 |
| 易測試性 | 需 Mock Servlet API (StrutsTestCase) | 直接 new Action()、set 屬性、呼叫方法,極易單測 |
| 輸入捕獲 | ActionForm (必須繼承基類) | Action 屬性直接接收,支援豐富對象圖 |
| 表達式語言 | JSTL EL (集合/索引弱) | OGNL (強大對象圖導航、投影、選擇) |
| 值綁定頁面 | JSP pageContext setAttribute | ValueStack (多層級上下文,同名不同類型屬性共存) |
| 類型轉換 | Commons-BeanUtils (全局配置) | OGNL 類型轉換器 (可實例級配置) |
| 驗證 | ActionForm validate() / Commons Validator | validate() + XWork 驗證框架 (字段/屬性/訪問器驗證,支援鏈式子屬性驗證) |
| Action 生命周期控制 | 模塊級 RequestProcessor (所有 Action 共享) | 攔截器棧 (每 Action 可定制棧) |
本文基於 Struts 2.0.6 撰寫,核心架構設計至今仍具參考價值。