DispatchAction Functionality in Struts 2

The DispatchAction Functionality is a way of grouping the related actions into a single action class. In struts 1 DispatchAction class provides this functionality but in struts 2 every action class by default provide this functionality. To achieve this functionality in struts 2 we have to define the actions with the different names but having the same signature as execute method.

Example:

test.jsp
<%@ taglib uri="/struts-tags" prefix="s"%>
<html>
<head>
<title>Struts 2 dispatch action functionality example</title>
</head>
<body>
<h3>This is a dispatch action functionality example.</h3>
 
<s:form action="TestAction">
<s:submit value="Submit"/>
<s:submit value="Show" action="testShow"/>
</s:form>
 
</body>
</html>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
>
 
 
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.ng.
filter.StrutsPrepareAndExecuteFilter
</filter-class>
</filter>
 
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
 
<welcome-file-list>
<welcome-file>test.jsp</welcome-file>
</welcome-file-list>
 
</web-app>
struts.xml
<!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="TestAction"
class="com.javawithease.action.TestAction">
<result name="success">/welcome.jsp</result>
</action>
 
<action name="testShow" method="show"
class="com.javawithease.action.TestAction">
<result name="success">/welcome.jsp</result>
</action>
 
</package>
 
</struts>
TestAction.java
import com.opensymphony.xwork2.ActionSupport;
 
/**
* This class is used as an action class.
* @author javawithease
*/

public class TestAction extends ActionSupport {
private String message;
 
public String execute(){
setMessage("execute method is called.");
return SUCCESS;
}
 
public String show(){
setMessage("show method is called.");
return SUCCESS;
}
 
public String getMessage() {
return message;
}
 
public void setMessage(String message) {
this.message = message;
}
}
welcome.jsp
<%@ taglib uri="/struts-tags" prefix="s"%>
<html>
<head>
<title>Struts 2 dispatch action functionality example</title>
</head>
<body>
<h3>This is a dispatch action functionality example.</h3>
 
<s:property value="message" />
 
</body>
</html>

Output:



When click on Submit button.


When click on Show button.

No comments: