DispatchAction class

    技术2022-05-11  118

    Class Dispatch is used to create actions that can handle more than one action which is execute(). Instead of using only execute() method, we can add many methods like add(), edit(), delete() in a action class.

    1. create class which extends org.apache.struts.actions.DispatchAction;2. config the action in struts-config.xml. We have to add a attribute parameter="method", and we have to refer to the method like /studentDispatchAction?method=add.3. using dispachtAction in .jsp files.

    A example:1.

    ------------------------------------------------------------StudentDispatchAction.java-----------------------------

    package  studentInfo; import  java.io.IOException; import  java.util.ArrayList; import  javax.servlet.ServletException; 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  StudentDispatchAction  extends  DispatchAction  public ActionForward add(ActionMapping mapping, ActionForm form,   HttpServletRequest request, HttpServletResponse response)   throws IOException, ServletException {  StudentForm stuForm = (StudentForm) form;  String stuID = stuForm.getStuID();  String name = stuForm.getName();  String gender = stuForm.getGender();  String age = stuForm.getAge();  ArrayList al = new ArrayList();  al.add(stuID);  al.add(name);  al.add(gender);  al.add(age);  String prompt;  StudentDAO stuDAO = new StudentDAO();  if (stuDAO.savaData(al)) {   prompt = "Success";  } else {   prompt = "Fail";  }  return mapping.findForward(prompt); }   public ActionForward edit(ActionMapping mapping, ActionForm form,    HttpServletRequest request, HttpServletResponse response)    throws IOException, ServletException {   //...      String prompt = "Fail";   return mapping.findForward(prompt);  }}

    ------------------------------------------------------------

    2. config struts-config.xml

         < action  input ="/studentInfo/register.jsp"  name ="studentForm"      path ="/studentDispatchAction"  scope ="request"      type ="studentInfo.StudentDispatchAction"  validate ="true"      parameter ="method" >       < forward  name ="Success"  path ="/studentInfo/success.jsp"       redirect ="true"   />       < forward  name ="Fail"  path ="/studentInfo/fail.jsp"  redirect ="true"   />      </ action >

    --------

    3. using it in .jsp files

    < html:form  method ="post"  action ="/studentDispatchAction?method=add" >

     

     


    最新回复(0)