Struts 作為經典 MVC 框架,Controller 層主要執行四大任務:
HTTP Request
↓
ActionServlet (Front Controller)
↓
RequestProcessor (處理流程模板方法)
↓
查找 ActionMapping (struts-config.xml)
↓
ActionForm 驗證/填充
↓
Action.execute() 業務處理
↓
返回 ActionForward
↓
RequestProcessor 轉向/重導向對應 JSP
↓
HTTP Response
HttpServlet,所有請求入口。process() 方法委派給 RequestProcessor。process() 定義標準流程骨架。processLocale():動態切換用戶語系(預設僅啟動時載入一次)。processActionPerform():調用 Action.execute()。processForward():處理 ActionForward 導向邏輯。<controller processorClass="com.example.MyRequestProcessor"/>public class LoginAction extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
// 1. 取得表單資料
LoginForm loginForm = (LoginForm) form;
// 2. 委派給 Service 層 (Model) - 絕不在 Action 寫業務邏輯!
UserService service = ServiceLocator.getUserService();
User user = service.authenticate(loginForm.getUsername(), loginForm.getPassword());
// 3. 放入請求/會話屬性供視圖使用
if (user != null) {
request.getSession().setAttribute("user", user);
return mapping.findForward("success");
} else {
// 4. 錯誤處理
ActionErrors errors = new ActionErrors();
errors.add("login", new ActionMessage("error.login.failed"));
saveErrors(request, errors);
return mapping.findForward("failure");
}
}
}
鐵律:Action 僅負責流程控制(參數轉換、Service 調用、結果導向),嚴禁包含業務邏輯。struts-example 範例專案將業務邏輯寫在 Action 中是反模式。
validate() 方法進行伺服器端驗證,失敗時自動返回輸入頁面顯示錯誤(配合 <html:errors/>)。request:請求結束即銷毀(預設,安全)。session:跨請求保留(適用於多步驟精靈表單)。<action-mappings>
<action path="/login" type="com.example.LoginAction" name="loginForm" scope="request" validate="true" input="/login.jsp">
<forward name="success" path="/welcome.do" redirect="true"/> <!-- 重導向防止重複提交 -->
<forward name="failure" path="/login.jsp"/>
</action>
</action-mappings>
ActionMapping.findForward("success") 會依序查找:Local Forward → Global Forward → 拋出異常。
| 標籤庫 URI | 前綴 | 主要用途 |
|---|---|---|
https://struts.apache.org/tags-bean | bean | Bean 存取、屬性輸出、訊息國際化 (bean:message, bean:write) |
https://struts.apache.org/tags-html | html | 表單生成 (html:form, html:text, html:select)、連結、錯誤顯示 (html:errors) |
https://struts.apache.org/tags-logic | logic | 流程控制 (logic:iterate, logic:present, logic:equal)、條件輸出 |
https://struts.apache.org/tags-template | template | 模板機制 (已被 Tiles 取代) |