Menu Home

Struts DispatchAction 类的使用

目的:将多个相关的业务封装在同一个Action中,从而避免工程中存在过多的Action

  • Action 的生成过程中要继承 DispatchAction
  • [singlepic id=61 w=320 h=240 float=none]

  • Action中没有execute()方法,取代的是多个业务方法
  • //Action 继承 DispatchAction
    public class ClacAction extends DispatchAction {
    	/*
    	 * 类中的方法自己取名字,并且禁止出现 execute()方法
    	 */
    
    	public ActionForward add(ActionMapping mapping, ActionForm form,
    			HttpServletRequest request, HttpServletResponse response) {
    		NumForm numForm = (NumForm) form;
    		// TODO Auto-generated method stub
    		NumEntity num = numForm.getNum();
    		ClacModel clac = new ClacModel();
    		System.out.println(clac);
    		request.setAttribute("result", clac.add(num.getA(), num.getB()));
    		return mapping.findForward("result");
    	}
    
    	public ActionForward sub(ActionMapping mapping, ActionForm form,
    			HttpServletRequest request, HttpServletResponse response) {
    		NumForm numForm = (NumForm) form;
    		// TODO Auto-generated method stub
    		NumEntity num = numForm.getNum();
    		ClacModel clac = new ClacModel();
    		request.setAttribute("result", clac.sub(num.getA(), num.getB()));
    		return mapping.findForward("result");
    	}
    }
  • 要在struts-config.xml中,为添加“parameter=”xxx””属性
  •     <!-- 为 action 添加参数 parameter -->
        <action
          parameter="clacM"
          attribute="numForm"
          name="numForm"
          path="/clac"
          scope="request"
          type="cn.net.royakon.action.ClacAction">
          <forward name="result" path="/result.jsp" />
        </action>
  • 在客户端指定要调用的业务方法
  • <!-- 方法1:使用表单提交 -->
    <%@ page language="java" pageEncoding="gb2312"%>
    <script type="text/javascript">
    <!--
    	function doSubmit(operate) {
    		document.forms[0].clacM.value = operate;
    		document.forms[0].submit();
    	}
    //-->
    </script>
    <form action="clac.do" method="post">
    	<!-- 表单中添加一个隐藏控件
    		 与配置文件sturts-config.xml中 action新添加属性对应以使struts识别关联
    		 name  = 新添加属性的值 parameter="clacM"
    		 value = Action 中用户自定义 Action 的方法名称
    	  -->
    	<input type="hidden" name="clacM" value=""/>
    	<table border="0" align="center">
    		<tr>
    			<td colspan="2">
    				<input type="text" name="num.a" />
    			</td>
    		</tr>
    		<tr>
    			<td colspan="2">
    				<input type="text" name="num.b" />
    			</td>
    		</tr>
    		<tr>
    			<td align="center">
    				<!-- 通过简单的 JAVASCRIPT 实现了表单的多向提交 -->
    				<input type="button" name="add" value=" + " onclick="doSubmit('add')" />
    			</td>
    			<td align="center">
    				<input type="button" name="sub" value=" - " onclick="doSubmit('sub')" />
    			</td>
    		</tr>
    	</table>
    </form>
    
    <!-- 方法2:使用超链接形式 -->
    <!-- 格式:Action路径名称?配置文件属性名称=用户自定义方法名称 -->
    <a href="clac.do?clacM=add">add</a>

Categories: 网页编程

Tagged as:

RoyAkon