DispatchAction class

The DispatchAction class provides a mechanism for modularizing a set of related functions into a single action, and thus eliminates the need to create separate, independent actions for each function. For example, consider a set of related functions for adding a user, updating a user, and removing a user. Instead of creating an AddUserAction class, an UpdateUserAction class, and a RemoveUserAction class, by extending DispatchAction, you can create one UserAction class that has three methods: add( ), update( ), and remove( ). At run time, DispatchAction manages routing requests to the appropriate method in its subclass. DispatchAction determines which method to call based on the value of a request parameter that is passed to it from the incoming request.
To use DispatchAction, you must create a subclass from it and provide a set of methods that will be called to process requests. Additionally, you have to set up for the action an action mapping that specifies the name of a request parameter that will be used to select which method should be called for each request.
 Following is an example UserAction class that extends DispatchAction:
package pack.nk;
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 UserAction extends DispatchAction
{
  public ActionForward add(ActionMapping mapping,
    ActionForm form,
    HttpServletRequest request,
    HttpServletResponse response)
    throws Exception
  {
    // Add user.
    …
    return new ActionForward("success");
  }
  public ActionForward update(ActionMapping mapping,
    ActionForm form,
    HttpServletRequest request,
    HttpServletResponse response)
    throws Exception
  {
    // Update user.
    …
    return new ActionForward("success");
  }
  public ActionForward remove(ActionMapping mapping,
    ActionForm form,
    HttpServletRequest request,
    HttpServletResponse response)
    throws Exception
  {
    // Remove user.
    …
    return new ActionForward("success");
  }
}

<action-mappings>
  <action path="/User"
          type="pack.nk.UserAction"
     parameter="function"/>
</action-mappings>

The value specified with the parameter attribute of the action tag will be used as the name of a request parameter that will contain the name of a method to invoke for handling the request. 

No comments:

Post a Comment