分散式企業應用架構複雜、技術棧多元,設計模式為可復用設計方案,對降低複雜度至關重要。MVC(Model-View-Controller)經 80 年代 Xerox PARC 提出,被 Sun 推薦為 J2EE 標準設計模式,廣泛應用於互動式應用系統。本文深入剖析 Apache Struts 如何實現 MVC,並以全面預算管理系統為實戰案例展示開發流程。

處理流程:Controller 接收請求 → 決定調用 Model → Model 處理業務邏輯回傳資料 → Controller 選擇 View 呈現結果。

核心技術:Servlet、JSP、Custom Tag Library。
ActionServlet:核心 Servlet,接收所有客戶端請求ActionMapping:配置式映射,將請求路徑對應至具體 Action 處理器Action:開發者繼承 org.apache.struts.action.Action 實作具體業務邏輯,調用業務元件,轉向適當 ViewActionForm:封裝客戶端表單資料,支援自動填充、驗證、重置,Action 直接讀寫屬性,無需操作 request/responseActionForm) 雙向映射,簡化 UI 開發功能:資料錄入、查詢、修改、刪除四大核心操作。
關鍵差異:
ActionForm 自動映射<%@ page contentType="text/html; charset=GBK" %>
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
<%@ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic" %>
<html:form action="/information/budgetinfoadd" enctype="multipart/form-data">
<html:select property="infoType" styleClass="input2">
<html:options collection="TypeList" property="id" labelProperty="typeName"/>
</html:select>
...
</html:form>
action 指定 Action 路徑,<html:form> 封裝表單資料,對應 Model 層 ActionForm。
public final class BudgetInfoAddForm extends ActionForm {
private String infoType; // 資料分類
private String title; // 資料標題
private String content; // 資料內容
private FormFile infoFile; // 資料檔案
// getter/setter 方法...
public void reset(ActionMapping mapping, HttpServletRequest request) {
title = null; content = null; infoFile = null;
}
}
模組實作四個 Action:
BudgetInfoAddAction - 資料錄入BudgetInfoContentAction - 資料查詢BudgetInfoUpdateAction - 資料修改BudgetInfoDelAction - 資料刪除ActionServlet 由 Struts 提供,開發者無需修改;重點在於開發具體 Action 類別,處理完業務邏輯後由 ActionServlet 轉向 JSP 頁面回傳結果。
web.xml:配置 Struts 核心 Servlet、過濾器、啟動參數struts-config.xml:定義 ActionMapping、Form Bean、全域轉向、資料來源等,串聯 MVC 三層透過雙配置檔將 Model、View、Controller 有機整合,構成完整 MVC 系統。
Struts 作為基於 MVC 的企業級 Web 應用框架,以完整文檔與相對簡潔架構著稱。內建標籤庫大幅提升開發效率,同時增強系統可維護性與擴充性。本文從原理到實戰案例完整展示 Struts 開發全流程,為後續專案應用提供參考基準。