JPetStore 是 Spring 官方示例項目,展示 Struts 1.x + Spring + iBATIS 輕量級 J2EE 架構。本文聚焦用戶管理模塊(登錄、註冊、編輯賬號),剖析 ActionForm 設計、Action 流程、Spring 整合要點。
<form-beans>
<!-- 登錄專用 -->
<form-bean name="accountForm" type="org.springframework.samples.jpetstore.web.struts.AccountActionForm"/>
<!-- 註冊/編輯專用 -->
<form-bean name="workingAccountForm" type="org.springframework.samples.jpetstore.web.struts.AccountActionForm"/>
<form-bean name="cartForm" type="..."/>
<form-bean name="emptyForm" type="..."/>
<form-bean name="workingOrderForm" type="..."/>
</form-beans>
同一 AccountActionForm 定義兩個實例,分離登錄與註冊/編輯的會話狀態,避免數據污染。
<action path="/shop/signonForm" type="...DoNothingAction" validate="false">
<forward name="success" path="/WEB-INF/jsp/struts/SignonForm.jsp"/>
</action>
<action path="/shop/signon" type="...SignonAction" name="accountForm" scope="session" validate="false">
<forward name="success" path="/shop/index.do"/>
</action>
DoNothingAction 直接轉發至登錄頁;SignonAction 處理提交,成功重定向首頁。
<action path="/shop/newAccountForm" type="...NewAccountFormAction" name="workingAccountForm" scope="session" validate="false">
<forward name="success" path="/WEB-INF/jsp/struts/NewAccountForm.jsp"/>
</action>
<action path="/shop/newAccount" type="...NewAccountAction" name="workingAccountForm" scope="session" validate="true" input="/WEB-INF/jsp/struts/NewAccountForm.jsp">
<forward name="success" path="/shop/index.do"/>
</action>
NewAccountFormAction 在 execute 中初始化 FormBean 放入 Session;NewAccountAction 開啟驗證,失敗自動返回輸入頁。
<action path="/shop/editAccountForm" type="...EditAccountFormAction" name="workingAccountForm" scope="session" validate="false">
<forward name="success" path="/WEB-INF/jsp/struts/EditAccountForm.jsp"/>
</action>
<action path="/shop/editAccount" type="...EditAccountAction" name="workingAccountForm" scope="session" validate="true" input="/WEB-INF/jsp/struts/EditAccountForm.jsp">
<forward name="success" path="/shop/index.do"/>
</action>
繼承 ActionForm,封裝通用字段校驗邏輯,子類僅需覆寫 validate() 即可複用。
public class BaseAction extends Action {
protected PetStoreFacade petStore; // 業務門面接口
@Override
public void setServlet(ActionServlet servlet) {
super.setServlet(servlet);
if (servlet != null) {
ServletContext ctx = servlet.getServletContext();
WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(ctx);
this.petStore = (PetStoreFacade) wac.getBean("petStore");
}
}
}
所有 Action 繼承 BaseAction,自動從 Spring 容器獲取業務 Bean petStore,實現 Web 層與 Service 層解耦。
BaseAction.setServlet() 統一初始化 Spring 上下文。PetStoreFacade 聚合多個 Service,為 Web 層提供粗粒度接口。validate="true/false" 控制是否觸發 FormBean 驗證,配合 input 屬性實現錯誤頁自動回顯。