Struts
:
DispatchAction
的使用
今天在看一個
Struts
代碼時,發現
Action
類繼承的父類為
DispatchAction
,于是找了找資料研究了下
DispatchAction
類,現總結如下:
DispatchAction
是
Struts1.1
中的一個類,它的父類是
Action
,它的作用就在于將多個功能相似的業務邏輯放在同一個
Action
中實現,各個業務邏輯通過傳入不同的參數來決定執行哪個操作方法
通常在
Action
中我們都是通過
execute
方法來處理業務邏輯及頁面轉向,一個
Action
只能完成一種業務邏輯處理
,
當然我們也可以在頁面插入一個隱藏的變量,然后在
Action
的
execute
方法中通過判斷這個隱藏變量的值來決定調用哪個方法,也可以達到同一個
Action
來處理多種業務邏輯,可是這樣的話想一想肯定會造成頁面代碼的增加及影響頁面代碼的可讀性
.
看一看
DispatchAction
是如何實現的
比如對一個用戶對象來說,存在增加,刪除,修改的操作,首先創建一個繼承
DispatchAction
的
UserAction
類,
然后將
addUser,delUser,updateUser
這些方法寫在這個類里面,代碼如下:
package
com.why.struts.action;
import
javax.servlet.http.HttpServletRequest;
import
javax.servlet.http.HttpServletResponse;
import
org.apache.struts.action.ActionForm;
import
org.apache.struts.action.ActionForward;
import
org.apache.struts.action.ActionMapping;
import
org.apache.struts.actions.DispatchAction;
import
com.why.Constant;
import
com.why.struts.form.AddUserForm;
import
com.why.struts.form.LoginForm;
public
class
UserAction
extends
DispatchAction
{
public
ActionForward addUser (ActionMapping mapping,ActionForm form,
HttpServletRequest request,HttpServletResponse response) throws Exception
{
//
增加用戶業務的邏輯
return
mapping.findForward(Constant.
FORWARD_ADD
);
}
public
ActionForward delUser(ActionMapping mapping,ActionForm form,
HttpServletRequest request,HttpServletResponse response) throws Exception
{
//
刪除用戶業務的邏輯
return
mapping.findForward(Constant.
FORWARD_SUCCESS
);
}
public
ActionForward updateUser(ActionMapping mapping,ActionForm form,
HttpServletRequest request,HttpServletResponse response) throws Exception
{
//
更新用戶業務的邏輯
return
mapping.findForward(Constant.
FORWARD_SUCCESS
);
}
}
如何實現這些不同方法的調用呢
?
那就是要在
struts-config.xml
文件中更改
action-mapping
的配置,如下:
<
action-mappings
>
<
action
attribute
=
"addUserForm"
input
=
"/addUser.jsp"
name
=
"addUserForm"
parameter="method"
path
=
"/addUser"
scope
=
"request"
type="com.why.struts.action.UserAction" >
</
action
>
<
action
attribute
=
"delUserForm"
input
=
"/delUser.jsp"
name
=
"delUserForm"
parameter="method"
path
=
"/delUser"
scope
=
"request"
type="com.why.struts.action.UserAction" />
<
action
attribute
=
"updateUserForm"
input
=
"/updateUser.jsp"
name
=
"updateUserForm"
parameter="method"
path
=
"/updateUser"
scope
=
"request"
type="com.why.struts.action.UserAction" />
</
action-mappings
>
可以看到每個
<action />
中都增加了
parameter=" "
項,這個值可以隨便命名,如上面命名為
metho
d
,用來接收頁面傳來的參數
如下為頁面的提交, 注意:對應
<action />
中的
parameter
值
,
對應
UserAction
類中的方法名
<html:link href="addUser.do?method=addUser">Add User</html:link>
DelUser.jsp
<html:link href="delUser.do?method=delUser">Add User</html:link>
UpdateUser.jsp
<html:link href="updateUser.do?method=updateUser">Add User</html:link>