DispachAction是動態的指定Action。也就是說在view層的不同的請求和url參數被ActionServlet所截獲,
並在struts-config.xml中根據請求得到參數不同來指定(調用)Action中不同的方法,根據方法的返回值來跳轉相應的頁面。
這樣可以很好的解決Action膨脹的問題。以前我們繼承struts中的Action只處理一種請求,也就是說不同的請求會有相應的Action類,這樣Action類就會越來越多,就會照成Action膨脹。用DispachAction會根據請求的不同來指定調用哪個方法,這樣可以有效的解決Action膨脹的問題。
如何使用DispachAction:
1.寫一個UserAction繼承DispachAction
寫一個addUser方法添加用戶
[java]
//添加User
public ActionForward addUser(ActionMapping mapping, ActionForm arg1,
HttpServletRequest arg2, HttpServletResponse arg3) throws Exception {
new UserService().saveUser(new User());
return mapping.findForward("ok");
}
//添加User
public ActionForward addUser(ActionMapping mapping, ActionForm arg1,
HttpServletRequest arg2, HttpServletResponse arg3) throws Exception {
new UserService().saveUser(new User());
return mapping.findForward("ok");
}
寫一個deleteUser方法刪除用戶
[java]
//刪除User
public ActionForward deleteUser(ActionMapping mapping, ActionForm arg1,
HttpServletRequest arg2, HttpServletResponse arg3) throws Exception {
return mapping.findForward("delok");
}
//刪除User
public ActionForward deleteUser(ActionMapping mapping, ActionForm arg1,
HttpServletRequest arg2, HttpServletResponse arg3) throws Exception {
return mapping.findForward("delok");
}
2.在頁面上
[html]
<SPAN style="FONT-SIZE: 18px"><form action="User.do?command=addUser" method="post">
username:<input type="text" name="username"><br>
password:<input type="password" name="password">
<input type="submit" value="提交">
</form>
<a href="User.do?id=1&command=deleteUser">刪除id為1的用戶</a></SPAN>
<form action="User.do?command=addUser" method="post">
username:<input type="text" name="username"><br>
password:<input type="password" name="password">
<input type="submit" value="提交">
</form>
<a href="User.do?id=1&command=deleteUser">刪除id為1的用戶</a>
3.在struts-config.xml配置
[html]
action-mappings>
<action path="/User"
parameter="command"
type="com.jxau.action.UserAction">
<forward name="ok" path="/add_ok.jsp"></forward>
<forward name="delok" path="/del_ok.jsp"></forward>
</action>
</action-mappings>
<action-mappings>
<action path="/User"
parameter="command"
type="com.jxau.action.UserAction">
<forward name="ok" path="/add_ok.jsp"></forward>
<forward name="delok" path="/del_ok.jsp"></forward>
</action>
</action-mappings>
總結:用DispatchAction可以動態的控制Action,根據一個模板一個Action的原則來管理一個業務邏輯。有效的防止Action膨脹的問題