Struts1的DispatchAction()方法

来源:互联网 发布:移动网络电视打开步骤 编辑:程序博客网 时间:2024/05/21 10:46

在早期的Struts 1.x中为了在大的工程下方便管理而添加了DispatchAction()方法

DispatchAction继承与Action类,是一个抽象类,封装了一些基础方法,来解决使用一个Action处理多个操作的能力,这就是DispatchAction最大的用途,它可以帮助我们用一个Action类,封装一套类似的操作方法,节省了类的数目,同时也减轻了后期维护的困难。

DispatchAction中主要包括以下几个方法:

        protected ActionForward dispatchMethod

  protected java.lang.reflect.Method getMethod

 

DispatchAction的使用有三步骤:

1.写一个类继承(extends)DispatchAction

package com.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;public class UserLogin extends DispatchAction{public ActionForward execute(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response)throws Exception {    System.out.println("主要的方法");return super.execute(mapping, form, request, response);}public ActionForward Login(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response)throws Exception {    System.out.println("这个是Login");    return mapping.findForward("welcome"); }   }

2.配置struts-comfig.xml文件

<action-mappings ><action path="/UserLogin"             name="userForm"             type="com.action.UserLogin"             parameter="action">          <forward name="welcome" path="/welcome.jsp"></forward>          <forward name="error" path="/index.jsp"></forward>      </action>  </action-mappings>

parameter的属性值是可以任意起的,只要你记得在传参数的时候统一就可以了。

3.调用自定义方法

可以有两种方式来调用:

第一种是以表单的方式

 <form action="UserLogin.do?action=Login" method="post"></form>

注意上面parameter的值和这里所使用的要一样,也就是上面所说的统一

第二种是隐藏域的形式

     <input type="hidden" name="oparator" value="Login" />

  然后用表单提交 那么 Struts xml配置文件中就改成

  <action path="/UserLogin" name="userForm" type="com.action.UserLogin" parameter="oparator">

  配置文件中的parameter 值就是jsp页面隐藏域的值

  其他的和Action的配置没有太大的区别 这里的名字是随便取的