In this tutorial you will learn how to group a set of related functions into a single action using Struts DispatchAction.
DispatchAction provides a mechanism for grouping a set of related functions into a single action, thus eliminating the need to create seperate actions for each functions. In this example we will see how to group a set of user related actions like add user, update user and delete user into a single action called UserAction.
The class UserAction extends org.apache.struts.actions.DispatchAction. This class does not provide an implementation of the execute() method as the normal Action class does. The DispatchAction uses the execute method to manage delegating the request to the individual methods based on the incoming request parameter. For example if the incoming parameter is "method=add", then the add method will be invoked. These methods should have similar signature as the execute method.
If you notice the signature of the add, update and delete methods are similar to the execute method except the name. The next step is to create an action mapping for this action handler. The request parameter name is specified using the parameter attribute. Here the request parameter name is method.
Now lets see how to invoke a DispatchAction from jsp. We have a simple form with three buttons to add, update and delete a user. When each button is clicked a different method in UserAction class is invoked.
Now consider the update and the delete button. The request parameter name specified in the action handler is "method". So this should be specified as the property name for the submit button. The name of the method to be invoked and the value of the button should be the same. So when the button is clicked the corresponding method in the UserAction will be called. The delete button shows an alternate way to specify the value of the button.
On executing the sample example the following page is displayed to the user.
When you click on add button the following page is displayed.
When you click on update button the following page is displayed.
You can download the source code of this example by clicking on the Download link below.