Are you bugged of creating separate action classes for some common set of functionality in your Struts application? Feeling pain in managing all those hundreds of Action classes in your project? Don’t worry, cheers..!! DispatchAction is for you.
DispatchAction is one of the Struts built-in action that provides a mechanism that facilitates having a set of related functionality in a single action instead of creating separate independent actions for each function.
Let us create a sample example that uses DispatchAction and implement certain functionality of our project. Before that, I assume you have working knowledge of Struts application. If you don’t, Read this tutorial about A Hello World Struts project and get some basics about Struts application.
Also, I assume you have already got a Struts application and you want to add Dispatch Action into it. So let us start with our example.
Step 1: Create DispatchAction class file.
Create an Action class called UserManagementAction and extend it with class org.apache.struts.actions.DispatchAction. Copy following code into it.
In above code, we have created separate methods (create(), delete(), update() and block()) for each functionality. Also note that the method signature of these methods are exactly similar to the execute() method of Action class file.
We have added an extra attribute in <action> tag, parameter=”parameter”. DispatchAction will read a request parameter called “parameter” and its value will decide the method to be called. Suppose you have a request parameter “parameter” with value “create”, Dispatch Action will call create() method from your Action file.
Step 3: Create JSPs for viewing the application.
Create two JSP files UserManagement.jsp and UserSuccess.jsp and copy following code into it. UserManagement.jsp will display a menu for selecting action to be taken. UserSuccess.jsp will just print the appropriate action taken by the Action class.
<%@tagliburi="http://jakarta.apache.org/struts/tags-html"prefix="html"%><html><head><title>Dispatch Action Example - viralpatel.net</title></head><body><h3>User Message (Dispatch Action Example)</h3><center><fontcolor="blue"><h3><%=request.getAttribute("message") %></h3></font><center></body></html>
In UserManagement.jsp, we have created links using <html:link> tag and passed a parameter “parameter” with values create, delete, block etc. This value is fetched by the Dispatch Action and is used to call corresponding method in Action class. Thus if we click Update User link, a parameter update will be passed to the action class and corresponding update() method will be called by framework.
Step 4: Run the application.
Compile and Run the project using Eclipse or Ant and open UserManagement.jsp file in your favorite browser.
Click the link Create User or Delete User etc. and see the output.