Struts DispatchAction Tutorial with Example in Eclipse.

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.
package net.viralpatel.struts.helloworld.action; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.actions.DispatchAction; public class UserManagementAction extends DispatchAction { public ActionForward create(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { request.setAttribute("message", "User created successfully"); return mapping.findForward("success"); } public ActionForward delete(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { request.setAttribute("message", "User deleted successfully"); return mapping.findForward("success"); } public ActionForward update(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { request.setAttribute("message", "User updated successfully"); return mapping.findForward("success"); } public ActionForward block(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { request.setAttribute("message", "User blocked successfully"); return mapping.findForward("success"); } }
Code language: Java (java)
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.
public ActionForward delete(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { }
Code language: Java (java)

Step 2: Create a mapping for action in struts-config.xml file.

Open your struts-config.xml and copy following action mapping entry in it.
<action path="/user" parameter="parameter" type="net.viralpatel.struts.helloworld.action.UserManagementAction"> <forward name="success" path="/UserSuccess.jsp" /> <forward name="failure" path="/UserSuccess.jsp" /> </action>
Code language: HTML, XML (xml)
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.

UserManagement.jsp

<%@taglib uri="http://jakarta.apache.org/struts/tags-html" prefix="html"%> <html> <head> <title>Dispatch Action Example - viralpatel.net</title> </head> <body> <h2>User Management (Dispatch Action Example)</h2> <html:link href="user.do?parameter=create">Create User</html:link> | <html:link href="user.do?parameter=delete">Delete User</html:link> | <html:link href="user.do?parameter=update">Update User</html:link> | <html:link href="user.do?parameter=block">Block User</html:link> </body> </html>
Code language: HTML, XML (xml)

UserSuccess.jsp

<%@taglib uri="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> <h3><%= request.getAttribute("message") %></h3> <center> </body> </html>
Code language: HTML, XML (xml)
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.

View Comments

  • @Carlos: Thanks for the good words :) Do read other articles about Struts and also feel free to subscribe for the newsletter.

  • If we have a from in which we are trying to use Dispatch action, What is the best way of implementing it. I have used the parameter in action tag of a Form, something like, action='dynaAction.do?param=ParamValue'. depends on the action selected, we can change the URL for the form. Do you have any other approach in doing this.

    Thanks,
    Kumar

  • hello viral
    my question is that ,cannot we use buttons instead of html-link ??.....
    b'coz when I m using buttons instead of links I m getting following error
    " Request[/ClientForm] does not contain handler parameter named 'parameter'. This may be caused by whitespace in the label text"....

    • Hi Neelam,
      The possible reason of error in case of using button instead of link is that it is not able to get parameter to decided which method to trigger in Struts. Create a field (hidden or select box) in your form with name="parameter" and set its value to method name that you want to call.

      Hope this will solve the issue.

  • hi viral
    I have tried this using
    **********jsp...************

    ***********struts-config...*************

    ********ApplicatonResources...***********
    label.save=save

    *********************ClientAction_Buttons.java***************************
    protected Map getKeyMethodMap() {
    Map map = new HashMap();
    map.put("label.add", "add");
    map.put("label.edit", "edit");
    map.put("label.search", "search");
    map.put("label.save", "save");
    return map;
    }

    public ActionForward add(
    ActionMapping mapping,
    ClientForm form,
    HttpServletRequest request,
    HttpServletResponse response) throws Exception {
    System.out.println("You are in add function.");
    return mapping.findForward("add");
    }
    **************

    but now I m getting the following error
    javax.servlet.ServletException: DispatchMapping[/ClientForm] does not define a handler property..
    can you please tell me what I doing wrong here???
    Regards
    Neelam

    • "javax.servlet.ServletException: DispatchMapping[/ClientForm] does not define a handler property..
      can you please tell me what I doing wrong here???"

      Your add() method is having a parameter of type ClientForm, Replace the ClientForm with ActionForm and check if it works.

  • I think this is not a good solution. In some situations it is not useful and cannot be implemented. How can we extend both ActionSupport and DispatchAction. In modern OOP, a class should be have one and only one superclass.

  • Hi viral,i am daily visitor of u r website,u r posts are very good and i am following the same.Me working as a s/w professional in a small organization.could you pls post one sample project with dao,vo,action,domain layer.

  • Hi Neelam,

    I guess, now you have used a hidden field named "parameter" on the jsp, but you have not
    created a property by the name "parameter" on the corresponding form for that jsp.

Share
Published by
Viral Patel
Tags: DispatchAction Struts struts dispatch action Tutorial

Recent Posts

  • Java

Java URL Encoder/Decoder Example

Java URL Encoder/Decoder Example - In this tutorial we will see how to URL encode/decode…

4 years ago
  • General

How to Show Multiple Examples in OpenAPI Spec

Show Multiple Examples in OpenAPI - OpenAPI (aka Swagger) Specifications has become a defecto standard…

4 years ago
  • General

How to Run Local WordPress using Docker

Local WordPress using Docker - Running a local WordPress development environment is crucial for testing…

4 years ago
  • Java

Create and Validate JWT Token in Java using JJWT

1. JWT Token Overview JSON Web Token (JWT) is an open standard defines a compact…

4 years ago
  • Spring Boot

Spring Boot GraphQL Subscription Realtime API

GraphQL Subscription provides a great way of building real-time API. In this tutorial we will…

4 years ago
  • Spring Boot

Spring Boot DynamoDB Integration Test using Testcontainers

1. Overview Spring Boot Webflux DynamoDB Integration tests - In this tutorial we will see…

4 years ago