DispatchAction in Struts

By: Grenfel Emailed: 1585 times Printed: 2041 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

DispatchAction is another useful built-in Struts Action. However you cannot use it as is. You will have to extend it to provide your own implementation. An example will make things clear. Consider an online credit card application. Customers fill the credit card application online. The bank personnel get a List screen as shown in Figure below and they can act in one of four ways - Approve, Reject or Add Comment. Consequently there are three images each being a <html:link>.

One way of dealing with this situation is to create three different Actions – ApproveAction, RejectAction and AddCommentAction. This is a valid approach, although not elegant since there might be duplication of code across the Actions since they are related. DispatchAction is the answer to this problem. With DispatchAction, you can combine all three Actions into one. The DispatchAction provides the implementation for the execute() method, but still is declared as abstract class. You start by sub-classing DispatchAction. Let us assume that CreditAppAction, a sub-class of DispatchAction is used to implement the above-mentioned presentation logic. It has four methods – reject(), approve() and addComment(). The CreditAppAction class definition is shown in Listing below.

You might be wondering why all the three methods take the same four arguments – ActionMapping, ActionForm, HttpServletRequest, HttpServletResponse. Don’t worry, you will find the answer soon.
For a moment, look at the four URLs submitted when the bank staff perform the three actions as mentioned before. They would look something like this.

 http://localhost:8080/bank/screen-credit-app.do?step=reject&id=2 
 http://localhost:8080/bank/screen-credit-app.do?step=approve&id=2    
 http://localhost:8080/bank/screen-credit-app.do?step=addComment&id=2

Figure: Screen Credit Applications page as seen by the bank staff.

An interesting thing to notice is that the value of the HTTP request parameter named step is same as the four method names in CreditAppAction. This is no coincidence. DispatchAction (the parent class of CreditAppAction) uses the value of the HTTP request parameter step to determine which method in CreditAppAction has to be invoked. In the execute() method, DispatchAction uses reflection to invoke the appropriate method in CreditAppAction. For this reason, the arguments on all the three methods in CreditAppAction are fixed and have to be – ActionMapping, ActionForm, HttpServletRequest, and HttpServletResponse in that order. Otherwise the method invocation by Reflection fails.

Okay, so part of the puzzle is solved. But how does DispatchAction know to look for the HTTP request parameter specifically named step in the URL? The simple answer is that it doesn’t. You will have to tell it explicitly. And this is done in the ActionMapping for /screen-credit-app.do. The ActionMapping for the URL path “/screen-credit-app.do” is declared in struts-config.xml as shown
in Listing below.

The section highlighted in bold is what makes this Action different from the rest. The type is declared as mybank.example.list.CreditAppAction – you already knew that. Now, let us look at the second attribute in bold. This attribute, named parameter has the value “step”. Notice that one of the HTTP request parameter in the four URLs is also named “step”. Now, it is all coming together. DispatchAction knows what parameter to look for in the incoming URL request through this attribute named parameter in struts-config.xml. From the value of parameter attribute, it knows the method to be invoked on the subclass. Since the arguments and their order in these methods is fixed by DispatchAction, the method invocation by reflection at runtime is successful. If for any reason, the arguments on these methods are different; the method invocation fails at runtime.

//Example DispatchAction 
public class CreditAppAction extends DispatchAction {
public ActionForward reject(ActionMapping mapping,
ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception
{
String id = request.getParameter(“id”);
// Logic to reject the application with the above id
... ... ...
mapping.findForward(“reject-success”);
}
public ActionForward approve(ActionMapping mapping,
ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception
{
String id = request.getParameter(“id”);
// Logic to approve the application with the above id
... ... ...
mapping.findForward(“approve-success”);
}
public ActionForward addComment(ActionMapping mapping,
ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception
{
String id = request.getParameter(“id”);
// Logic to view application details for the above id
... ... ...
mapping.findForward(“viewDetails”);
}
...
...
}\

DispatchAction can be confusing in the beginning. But don’t worry. Follow these steps to setup the DispatchAction and familiarize yourself with the steps.

  1. Create a subclass of DispatchAction.
  2. Identify the related actions and create a method for each of the logical actions. Verify that the methods have the fixed method signature shown earlier.
  3. Identify the request parameter that will uniquely identify all actions.
  4. Define an ActionMapping for this subclass of DispatchAction and assign the previously identified request parameter as the value of the parameter attribute.
  5. Set your JSP so that the previously identified request parameter (Step 3) takes on DispatchAction subclass method names as its values.

//Action Mapping for the DispatchAction
<action path="/screen-credit-app"
input="/ListCreditApplications.jsp"
type="mybank.example.list.CreditAppAction"
parameter="step"

scope="request"
validate="false">
<forward name="reject-success"
path="RejectAppSuccess.jsp"
redirect="true"/>
..
</action>

Design Tip: Use DispatchAction when a set of actions is closely related and separating them into multiple Actions would result in duplication of code or usage of external helper classes to refactor the duplicated code. In the above example DispatchAction was used handle hyperlinks. DispatchAction is a good choice when there are form submissions using the regular buttons (not the image buttons). Just name all the buttons same. For instance,

<html:submit property=”step”>Update</html:submit>
<html:submit property=”step”>Delete</html:submit>

and so on. Image buttons is a different ball game. Image button usage for form submission and DispatchAction are exclusive. You have to choose one. In the above example we used the DispatchAction and used methods that has ActionForm as one of its arguments. As you learnt in the last chapter, an ActionForm always existed in conjunction with the Action. In the Listing above, all the four methods got a null ActionForm. But that did not matter since the HTTP request parameters were used directly in the Action. You can have a Form bean if there are a lot of HTTP parameters (and perhaps also require validation). The HTTP parameters can then be accessed through the Form bean.


Struts Home | All Struts Tutorials | Latest Struts Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.



Bookmark and Share

Comments(5)


1. View Comment

this tutorial is very nice but if it contains more gui figure examples,it wil very nice

View Tutorial          By: JOHN.J at 2007-11-29 23:56:06
2. View Comment

Very nice to understand the concept.It also help the learner as well as experienced java people.

View Tutorial          By: Hrusikesh jena at 2011-05-26 00:23:28
3. View Comment

Hi Friends,

I got a very interesting url for this topic. Try it. It contains nice explanation of Dispatch Action with code.
http://www.raistudies.com/struts-1/dispatchaction/


View Tutorial          By: Rohit Kapur at 2011-07-27 20:56:57
4. View Comment

Following question to this topic:
- when in a dispatch action I am unable to pass a field parameter and it's value within the URL.
-projectID works, teamID does not work
- teamID is entered by the user in the input field

I was trying to get the value via javascript, but I read that the action is evaluated before the javascript.



Here my code:
<input type="text" name="tsid" id="tsid" maxlength="100" />
<li>
<a href="<@s.url action='deleteTeam' value='deleteTeam.jspa'>
<@s.param name="projectID" value="${projectID?c}"/>
<@s.param name="teamID" value="javascript: document.getElementById('tsid').value"/>
</@s.url>">
<@s.text name="delete Team" /></a>
</li>


View Tutorial          By: Alistair at 2012-01-14 10:59:52
5. View Comment

nice tutorial,but if provided with the complete example with out put then it would be help full for the viewers.

View Tutorial          By: Prasant Kumar Sahu at 2013-01-07 13:17:20

Your name (required):


Your email(required, will not be shown to the public):


Your sites URL (optional):


Your comments:



More Tutorials by Grenfel
Verifying a Signed JAR File example
Bitwise and Bit Shift Operators example in Java
JavaBeans Basic Concepts
The Differences Between Simple and Classic Tags in JSP
Bitwise Logical Operators in C
DispatchAction in Struts
union example program in C
Comparison operators in JSP
Basics of Structures in C
register Variables in C
Struts and Tiles - Steps to use Struts and Tiles
The if else statement in C
Character Counting sample program in C
Installing JSF
cin.ignore() in C++

More Tutorials in Struts
Configuring JDBC DataSources in Struts
Struts Classes
FAQ: Why was reload removed from Struts (since 1.1)?
FAQ: Why are my checkboxes not being set from ON to OFF?
Using JavaScript to submit a form in Struts
How to prepopulate a form in Struts
Simple example of using the requiredif Validator rule in Struts
Chaining actions in Struts
When is the best time to validate input in Struts
What is a Plug-in and how to use Java plug-ins with Struts?
7 Best Practices of Struts
Origin and Architecture of Struts
ActionErrors and ActionError in Struts
Tutorial on Struts Configuration File - struts-config.xml in Struts - from the book: Struts Survival Guide. Basics to Best Practices
Handling multiple buttons in HTML Form in Struts

More Latest News
Most Viewed Articles (in Struts )
Tutorial on Struts Configuration File - struts-config.xml in Struts - from the book: Struts Survival Guide. Basics to Best Practices
What is Struts? Which Version of Struts to use?
Handling Duplicate Form Submissions in Struts
Creating Struts Modules
Configuring JDBC DataSources in Struts
Using JavaScript to submit a form in Struts
Chaining actions in Struts
Installing and configuring Tomcat and Struts
Editing web.xml in a Struts Application
Struts 1 vs Struts 2
Struts and Tiles - Steps to use Struts and Tiles
ActionErrors and ActionError in Struts
Protecting JSPs from direct access in Struts
Simple example of using the requiredif Validator rule in Struts
What is a Model View Controller (MVC) Model?
Most Emailed Articles (in Struts)
Downloading and installing Struts
The directories and files of a Struts application
Editing web.xml in a Struts Application
Editing struts-config.xml in a Struts Application
Creating the first application using Struts 2
Model 1 Architecture
MVC Architecture (Model 2 Architecture)
Installing and configuring Tomcat and Struts
Guidelines for Struts Application Development
Using Checkbox & Radio Tags, html:select, html:options in Struts Forms
Tutorial on Struts Configuration File - struts-config.xml in Struts - from the book: Struts Survival Guide. Basics to Best Practices
ForwardAction in Struts
Using JavaScript to submit a form in Struts
What is Struts? Which Version of Struts to use?
History of Struts