Programming Tutorials

DispatchAction in Struts

By: Grenfel in Struts Tutorials on 2023-05-04  

DispatchAction is a Struts Action class that helps in handling multiple requests in a single action. It is useful when a single Action class is needed to handle multiple related requests, which would otherwise require multiple Action classes.

To use DispatchAction in Struts, the following steps need to be performed:

  1. Extend the DispatchAction class to create a new Action class.
  2. Override the methods of the DispatchAction class to handle the individual requests.
  3. Define the request parameter that will be used to determine which method to invoke.
  4. Map the new Action class in the struts-config.xml file.

Here's an example of how to use DispatchAction in Struts:

public class MyDispatchAction extends DispatchAction {

    public ActionForward add(ActionMapping mapping, ActionForm form,
                             HttpServletRequest request, HttpServletResponse response) throws Exception {
        // Add logic here
        return mapping.findForward("success");
    }

    public ActionForward edit(ActionMapping mapping, ActionForm form,
                              HttpServletRequest request, HttpServletResponse response) throws Exception {
        // Edit logic here
        return mapping.findForward("success");
    }

    public ActionForward delete(ActionMapping mapping, ActionForm form,
                                HttpServletRequest request, HttpServletResponse response) throws Exception {
        // Delete logic here
        return mapping.findForward("success");
    }
}

In the struts-config.xml file, the new Action class can be mapped like this:

<action path="/myAction" type="com.example.MyDispatchAction">
    <parameter name="method" value="add" />
    <parameter name="add" value="com.example.AddForm" />
    <forward name="success" path="/success.jsp" />
</action>

In this example, the "method" parameter is used to determine which method to invoke in the MyDispatchAction class. The "add" parameter specifies the form bean to use for the "add" method. The "success" forward is used to navigate to the success.jsp page after the action is performed.






Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in Struts )

Latest Articles (in Struts)