使用DispatchAction類,為系統減肥!
在
Struts
中你要盡可能的不用
Action
類,因為他們讓你的項目變得臃腫,你可以使用
org.apache.struts.actions.DispatchAction
類來完成業務邏輯所需要的相關操作集中到一個
Action
類中,在繼承
DispatchAction
后,你不再是重新定義
execute()
方法,而是編寫你自己的業務方法,
execute()
方法在
DispatchAction
抽象類定義。
例如我們可以繼承
DispatchAction
來定義一個
AccountAction
,在當中集中管理一些與賬號相關的操作,如下:
package com.fasttalk;
import javax.servlet.http.*;
import org.apache.struts.action.*;
import org.apache.struts.actions.*;
?????????????????????????????????????????????????????????
public class AccountAction extends DispatchAction {
??? public ActionForward login(ActionMapping mapping,
????????????????????????????? ActionForm form,
????????????????????????????? HttpServletRequest request,
????????????????????????????? HttpServletResponse response)
??? throws Exception {
??????? // login相關的操作
??????? ......
??? }
????public ActionForward logout(ActionMapping mapping,
??????????????????????????????? ActionForm form,
??????????????????????????????? HttpServletRequest request,
??????????????????????????????? HttpServletResponse response)
??? throws Exception {
??????? // logout相關的操作
??????? ......
??? }
????public ActionForward method1(ActionMapping mapping,
??????????????????????????????? ActionForm form,
???? ???????????????????????????HttpServletRequest request,
??????????????????????????????? HttpServletResponse response)
??? throws Exception {
??????? // method1相關的操作
??????? ......
???? }
???......
}
我們不再重新定義execute()方法,而是定義我們自己的login()、logout()等方法,
這些方法接收與execute()相同的參數,并且也傳回ActionForward對象。
使用DispatchAction時,我們要在struts-config.xml定義:
<ACTION
??????????? path="/account"
??????????? type="com.fasttalk.AccountAction"
??????????? parameter="method"
??????????? name="userForm">
使用方法:
通過參數method= method1 來選擇函數
<%
??????
String dest = " account.do?method= method1";
???response.sendRedirect(dest);%>