Struts DispatchAction
在1.0版本中我們通常都是用execute方法來完成我們對業務邏輯的處理及頁面的轉發。通常在一個Action中我們都只能夠完成一種業務邏輯的操作。如果要是完成多個業務邏輯(比如:添加、刪除等)功能相近的業務邏輯我們就沒有辦法了么?答案是否定的,我們可以通過在頁面中定義一個隱藏變量,在不同的頁面要求處理不同的業務邏輯的時候我們可以賦予這個變量不同的值,并在execute方法中通過對變量值的判斷來完成不同的業務邏輯操作。
舉例來說,我們首先在頁面中定義一個隱藏變量。
<html:hidden property="operAt"/>
然后定義一個JavaScript函數,我們可以在通過點擊提交按鈕的時候,在函數體里面修改它的值。
<SCRIPT>
function set(key) {
????with(document.forms[0]){
??????operAt.value=key;
????}
}
</SCRIPT>
當我們點擊提交按鈕便觸發該事件,修改變量的值。
<html:submit οnclick="set('save');">SAVE</html:submit>
那我們在后臺execute中又如何處理相關邏輯呢?
String operAt = myForm.getOperAt();
if (operAt.equals("create")) { ...
if (operAt.equals("save")) { ...
雖然說這樣做我們可以實現多個業務邏輯在同一個Action中實現,可是帶來的代價便是代碼的冗長,不易理解。
DispatchAction是僅次于Action,使用最頻繁的Action,用于同一個表單中有兩個請求提交按鈕時,但提交需要的邏輯處理完全不同的情況。
DispatchAction可支持多個處理邏輯。
實現DispatchAction的步驟:
1在JSP頁面中增加隱藏字段
<input type="hidden" name="method" value="add"/>
<input type="submit" value='<bean:message key="button.add"/>'??onClick="method.value='add'"/>????????
<input type="submit" value='<bean:message key="button.modify"/>' onClick="method.value='modify'"/>????????
<input type="reset" value='<bean:message key="button.reset"/>'/>
2在struts-config.xml中的action配置中,增加parameter屬性,用于指定參數名
<action path="/login" type="lee.LoginAction" name="loginForm"
?? scope="request" validate="true" input="/login.jsp" parameter="method">
?? <forward name="success" path="/welcome.jsp"/>
</action>
3在Action中的實現
public class LoginAction extends DispatchAction
{
????public ActionForward add(ActionMapping mapping, ActionForm form,
?????? HttpServletRequest request, HttpServletResponse response)throws Exception
????{
????????System.out.println("增加");
????????request.setAttribute("method" , "增加");
????????return mapping.findForward("success");
????}
????public ActionForward modify(ActionMapping mapping, ActionForm form,
?????? HttpServletRequest request, HttpServletResponse response)throws Exception
????{
????????System.out.println("修改");
????????request.setAttribute("method" , "修改");
????????return mapping.findForward("success");
????}
}
總結
以上是生活随笔為你收集整理的Struts DispatchAction的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Struts 动态Form的验证框架步骤
- 下一篇: 关于base标签