Pages Navigation Menu

Coding is much easier than you think

DispatchAction Functionality in Struts 2

 
In Struts 1 DispatchAction helps us in grouping a set of related functions into a single action. In Struts 2 all the Actions by default provide this functionality. To use this functionality we need to create different methods with the similar signature of the execute() method.
 
Dispatchaction functionality in struts 2
 
In our example the CalculatorAction class has all the methods related to a Calculator like add(), multiply(), division() and subtract() which are used for performing mathematical operation on two numbers and it displays the result in a single jsp based on the action button clicked in jsp.
 
** UPDATE: Struts 2 Complete tutorial now available here.
 

Action Class

 

package com.simplecode.action;

import com.opensymphony.xwork2.Action;

public class CalculatorAction implements Action 
{	
private float number1;
private float number2;
private float result;
private String methodName;

	public String execute() 
	{
		number1 = 0;
		number2 = 0;
		result = 0;
		setMethodName("execute Method");
		return SUCCESS;
	}

	public String add() 
	{
		result=number1+number2;
		setMethodName("add Method");
		return "add";
	}

	public String subtract() 
	{
		result = number1 - number2;
		setMethodName("subtract Method");
		return "subtract";
	}

	public String multiply() 
	{
		result = number1 * number2;
		setMethodName("multiply Method");
		return "multiply";
	}

	public String divide() 
	{
		if(number2!=0)
			result = number1/number2;
		else if(number1!=0)
			result = number2/number1;
		else
			result=0;
		
		setMethodName("divide Method");
		return "divide";
	}

	public float getNumber1() {
		return number1;
	}

	public void setNumber1(float number1) {
		this.number1 = number1;
	}

	public float getNumber2() {
		return number2;
	}

	public void setNumber2(float number2) {
		this.number2 = number2;
	}

	public float getResult() {
		return result;
	}

	public void setResult(float result) {
		this.result = result;
	}

	public String getMethodName() {
		return methodName;
	}

	public void setMethodName(String methodName) {
		this.methodName = methodName;
	}
}

 
Recommended Article

 

Struts.xml

 
Here in order to do a DispatchAction functionality we need to create separate action mapping for each method in the action class, which is done in the struts.xml as shown below.
 

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>

<package name="default" extends="struts-default">

	<action name="Number" class="com.simplecode.action.CalculatorAction">
		<result name="success">/curd.jsp</result>
	</action>
	<action name="addNumber" method="add"
		class="com.simplecode.action.CalculatorAction">
		<result name="add">/curd.jsp</result>
	</action>
	<action name="multiplytNumber" method="multiply"
		class="com.simplecode.action.CalculatorAction">
		<result name="multiply">/curd.jsp</result>
	</action>
	<action name="subtractNumber" method="subtract"
		class="com.simplecode.action.CalculatorAction">
		<result name="subtract">/curd.jsp</result>
	</action>
		<action name="divideNumber" method="divide"
		class="com.simplecode.action.CalculatorAction">
		<result name="divide">/curd.jsp</result>
	</action>

</package>
</struts>

 
Here note that we use the same action class in all the action mappings but only the method name differs. So now When the request URL is “Number” the execute() method in the CalculatorAction class will be executed. When the request URL is “addNumber” the add() method in the CalculatorAction class will be invoked, this is specified using the method attribute of the action tag in struts xml. Similarly for subtract, multiply and divide request the subtract() ,multiply() and divide() methods will be invoked respectively.
 
This way configuring a separate action mapping for each method of same action class can be avoided by using a feature called Dynamic Method Invocation. We will learn about this in our upcoming tutorial.
 

Jsp

 

In the curd.jsp page we create five different buttons to invoke the different methods in the CalculatorAction class.
 

<%@taglib uri="/struts-tags" prefix="s"%>
<html>
<head>
<title>Dispatch Action</title>
</head>
<body>
<s:form action="Number">
<table>
	<tr><td><s:textfield name="number1" label="Number 1 " id="number1"/></td></tr>
	<tr><td><s:textfield name="number2" label="Number 2 " id="number2"/></td></tr>
	<tr><td><s:textfield name="result" label="Result " readonly="true" /></td></tr>
	<tr>
        <td><s:textfield name="methodName" label="Method involked " readonly="true" /></td>
        </tr>
	<tr>
	    <td><s:submit action="addNumber" value="Add" align="left"/></td>
       	    <td><s:submit action="subtractNumber" value="Subtract" align="left"/></td>
	    <td><s:submit action="divideNumber" value="Divide" align="left"/></td>
	    <td><s:submit action="multiplytNumber" value="Multiply" align="left"/></td>
	    <td><s:submit align="left"/></td>	
	</tr>
</table>
</s:form>
</body>
</html>

 
On running the example the following page will be displayed in the browser. Now when the user click a button the appropriate method in the CalculatorAction class gets invoked.
 
DispatchAction
 

For example When the user clicks the add button the add() method in the CalculatorAction class gets executed and the following page is displayed.
 
DispatchAction Method
 

Note: Dispatch action functionality is used when you have multiple submit buttons in a single form.

 
download

About Mohaideen Jamil


Am currently working as a Struts 2 Developer in a reputed IT Organisations. I can help you with teaching Core java and Struts 2. Follow me on Facebook or Google Plus. If you like my tutorials, consider making a donation to this charity, thanks.

  • Kuo Chaohung

    Hi Jamil

    I just found the latest Struts2(struts2-core-2.3.24.jar, xwork-core-2.3.24) does not support this and wildcard mehod to invoke different methods in the Action class.

    It will always invoke execute().
    However you library works fine, thank you.

    • http://www.simplecodestuffs.com/ Mohaideen Jamil

      Thanks for the update:)

  • Chandu

    Hi Jamil,

    Iam very new to struts and your tutorial helped me alot. But every time when I try to click on any submit button, only execute method is called and shows 0 result.
    I observed the following warning while running the code.

    WARNING: Parameter [action:addNumber] is on the excludeParams list of patterns!

    Please help in resolving it.

  • Jagannath

    Hi, how can I upload “Photo” and “signature” images and display on clicking “view Photo” and “View Sign” submit buttons on same JSP page using struts2. I have taken another submit button for form submission. if I click on any submit button it is displaying images.I have used like action=”photoUpload” for submit buttons and written upload and display images code in action class in two methods like photo() and sign() and . In struts.xml file ……
    How can I solve this problem.

    Thanks and Regards,
    Jagannath

    • http://www.simplecodestuffs.com Mohaideen Jamil

      If my guess is right, ur execute method or the method in your form get triggered when you click on any submit button.. I got similar kind of issue once, so as an alternate , instead of giving action name in submit button, i implemented it via java script files. i.e on click of a particular submit button, try to call a specific action….

  • SURESH

    Hi jamil,
    In the abov example without using the value attribute how the values are set to the textfiels. please clear this doubt. Thanks in Advance.

  • suresh

    Hi one thing i need understand jamil. In the submit button you have specified action attribute then for what you have mentioned action attribute in form. That thing i need not understand. Please help me to understand

    • http://www.simplecodestuffs.com Mohaideen Jamil

      It is used when there is no action attribute in the submit button.. In the above jsp for the submit button ->
      [code]

      [/code]
      Action attribute specified in the form gets invoked.

      • suresh

        Hi jamil.. In the above example i tried by removing action attribute in form tag. It is not working..I m getting the o/p page with no values in text fields

  • Gundamaiah

    Hi Jamil,

    Great Tutorial.Its really helps me.

    But after clicking add.Its giving correct result.But after clicking subtract immediately .Its giving 4o4 error page.Please tell me how to avoid this.

    • Jamil

      Hi Gundamaiah,
      This example works fine, may be you would have set namespace tag in package wrongly. I have attached the sample project for reference.(refer download link)

    • Jamil

      Hi Gundamaiah,

      I have updated war file in this post today (refer download link)

      Hope it helps you:)