首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

WebWork 2 架構全景解析:從 HTTP 請求到 Action 執行的完整流程與核心組件

     編輯:Java 相關知識

前言

WebWork 2 (Struts 2 前身) 採用 **WebWork 2 + XWork 1** 雙層架構,徹底分離 Web 層與核心控制層。本文從宏觀角度梳理完整請求處理流程與關鍵組件職責。

架構分層

層次模組核心職責
Web 層WebWork 2HTTP 請求接收、參數/Session/Application Map 化、Servlet API 隔離、結果渲染 (JSP/Velocity/FreeMarker)
核心層XWork 1Action 管理、攔截器鏈調度、OGNL 值棧、類型轉換、驗證、IoC 容器整合

完整請求處理流程

  1. ServletDispatcher.service():接收 HttpServletRequest/Response,解析 namespace、actionName。
  2. createContextMap():將 request/session/application/parameters 封裝為 Map (即 ActionContext),保留原始 request/response 供極少數需求。
  3. ActionProxyFactory.createActionProxy():根據 namespace+actionName 查找 ActionConfig,建立 DefaultActionProxy 與 DefaultActionInvocation。
  4. DefaultActionInvocation.init():
    • 建立 ActionContext (含值棧)。
    • ObjectFactory 實例化 Action。
    • 讀取攔截器清單 (來自 xwork.xml 或註解)。
  5. DefaultActionInvocation.invoke():責任鏈模式依序執行攔截器:
    • ParametersInterceptor:請求參數 → OGNL → Action/Model 屬性。
    • ModelDrivenInterceptor:模型物件壓入值棧頂端。
    • ValidationInterceptor:執行驗證邏輯。
    • WorkflowInterceptor:驗證失敗時返回 INPUT 結果。
    • ... 自訂攔截器 ...
  6. Action 邏輯執行:攔截器鏈末端呼叫 action.execute() (或指定方法)。
  7. Result 執行:根據返回代碼 (SUCCESS, ERROR, INPUT 等) 查找 ResultConfig,執行對應 Result 實作 (DispatcherResult → JSP, VelocityResult, StreamResult 等)。
  8. 回應輸出:Result 直接寫入 HttpServletResponse。

核心組件關係圖

HttpServletRequest
       │
       ▼
ServletDispatcher (Front Controller)
       │
       ├─► createContextMap() → Map (ActionContext)
       │
       ▼
ActionProxyFactory → DefaultActionProxy
       │
       ▼
DefaultActionInvocation (Dispatcher)
       │
       ├─► Interceptor Chain (AroundInterceptor template)
       │       ├─ ParametersInterceptor
       │       ├─ ModelDrivenInterceptor
       │       ├─ ValidationInterceptor
       │       └─ ...
       │
       ▼
Action (POJO, 可選實作 ModelDriven, Validateable)
       │
       ▼
Result (View Rendering)
       │
       ▼
HttpServletResponse

關鍵設計哲學

  1. POJO Action:Action 無需繼承基類、實作介面,僅需提供執行方法,極易單元測試。
  2. 攔截器即 AOP:橫切關注點 (參數綁定、驗證、事務、日誌、權限) 模組化、可重用、可配置排序。
  3. 值棧統一存取:OGNL 表達式統一存取 Action、Model、Request、Session、Application,視圖層零程式碼。
  4. 類型轉換集中化:XWorkConverter + TypeConverter 註冊機制,消除 Action 中重複解析邏輯。
  5. IoC 友善:ObjectFactory 介面支援 Spring、PicoContainer、Guice 整合,Action 依賴自動注入。

遷移至 Struts 2 注意事項

  • Struts 2 = WebWork 2.2+ 重新品牌,核心架構不變。
  • 套件名稱變更:com.opensymphony.webwork → org.apache.struts2,com.opensymphony.xwork → com.opensymphony.xwork2。
  • 配置檔:webwork.properties → struts.properties,xwork.xml → struts.xml。
  • 標籤庫:<ww:form> → <s:form>,功能相容並增強。
  • 結語

    WebWork 2 的架構設計在當時極具前瞻性:**Servlet 解耦、POJO Action、攔截器 AOP、OGNL 統一存取**,直接影響了後續 Struts 2、Spring MVC、甚至現代響應式框架的設計思路。深入理解其源碼,有助於掌握 Java Web 框架的核心演進脈絡。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved