在1.0版本中我们通常都是用execute方法来完成我们对业务逻辑的处理及页面的转发。通常在一个Action中我们都只能够完成一种业务逻辑的操作。如果要是完成多个业务逻辑(比如:添加、删除等)功能相近的业务逻辑我们就没有办法了么?答案是否定的,我们可以通过在页面中定义一个隐藏变量,在不同的页面要求处理不同的业务逻辑的时候我们可以赋予这个变量不同的值,并在execute方法中通过对变量值的判断来完成不同的业务逻辑操作。 举例来说,我们首先在页面中定义一个隐藏变量。 <html:hidden property="operAt"/> 然后定义一个JavaScript函数,我们可以在通过点击提交按钮的时候,在函数体里面修改它的值。 <SCRIPT> function set(key) { with(document.forms[0]){ operAt.value=key; } } </SCRIPT> 当我们点击提交按钮便触发该事件,修改变量的值。 <html:submit onclick="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"); }}
本文转自左正博客园博客,原文链接:http://www.cnblogs.com/soundcode/archive/2010/12/20/1911909.html,如需转载请自行联系原作者