ActionServlet (Front Controller)。ActionServlet 依 struts-config.xml 中的 <action-mapping> 找到對應 Action 類別。Action 執行商業邏輯 (呼叫 EJB/DAO/Service),結果存入 ActionForm。Action 回傳 ActionForward,導向 JSP 視圖。struts-config.xml 建立映射表。ActionServlet 注入應用級初始化邏輯。<action-mappings>
<action path="/login" type="com.app.LoginAction" name="loginForm" scope="request">
<forward name="success" path="/welcome.jsp"/>
<forward name="failure" path="/login.jsp"/>
</action>
</action-mappings>
path:請求路徑;type:Action 實作類;name:對應 Form Bean;scope:request/session。org.apache.struts.action.ActionForm,提供 reset()、validate() 鉤子。Action.execute()。public class LoginAction extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest req, HttpServletResponse res) {
LoginForm lf = (LoginForm) form;
User user = UserService.authenticate(lf.getUsername(), lf.getPassword());
if (user != null) {
req.getSession().setAttribute("user", user);
return mapping.findForward("success");
}
return mapping.findForward("failure");
}
}
Struts 不強制 Model 實作介面,建議使用 POJO Service + DAO,Action 僅負責協調與轉發。
| 標籤庫 URI | 功能焦點 | 常用標籤 |
|---|---|---|
/tags/struts-html | 表單、連結、圖片、JavaScript 整合 | <html:form>, <html:text>, <html:submit> |
/tags/struts-bean | Bean 屬性輸出、迭代、定義變數 | <bean:write>, <bean:iterate>, <bean:define> |
/tags/struts-logic | 條件判斷、迴圈、流程控制 | <logic:present>, <logic:iterate>, <logic:redirect> |
/tags/struts-template | 頁面模板、版面複用 | <template:insert>, <template:put> |
JSP 頂部宣告:<%@ taglib uri="/tags/struts-html" prefix="html" %>
servlet.jar、jdbc2_0-stdext.jar (DataSource 支援)。struts.jar、commons-*.jar 放入 WEB-INF/lib。struts-*.tld 放入 WEB-INF,於 web.xml 宣告 <taglib>。web.xml:ActionServlet 與 *.do 映射。struts-config.xml 定義 ActionMapping、Form Bean、Forward、DataSource。