July 5, 2011

DispatchAction functionality in Struts2

In Struts 1.x, the in-built DispatchAction action allows us to group similar functional actions/requests into a single action.

1) In Struts 2, every action class is equipped to provide this functionality. First, there should be several methods (based on functions) similar in signature to the execute() method in the action class.

package info.icontraining.struts2;

import com.opensymphony.xwork2.*;

public class UserAction extends ActionSupport {

   private String message;

   public String execute() {
      message = "Inside execute method";
      return SUCCESS;
   }

   public String add() {
      message = "Inside add method";
      return SUCCESS;
   }

   public String update() {
      message = "Inside update method";
      return SUCCESS;
   }

   public String delete() {
      message = "Inside delete method";
      return SUCCESS;
   }

   public String getMessage() {
      return message;
   }

   public void setMessage(String message) {
      this.message = message;
   }
}

2) For each of the additional methods such as add(), update(), etc., other than the execute() method, that we would want to be executed on a client invocation, add a separate <action> element configuration in the struts.xml file

<action name="User" class="info.icontraining.struts2.UserAction">
   <result name="success">/success.jsp</result>
</action>

<action name="addUser" method="add" class="info.icontraining.struts2.UserAction">
   <result name="success">/success.jsp</result>
</action>

<action name="updateUser" method="update" class="info.icontraining.struts2.UserAction">
   <result name="success">/success.jsp</result>
</action>

<action name="deleteUser" method="delete" class="info.icontraining.struts2.UserAction">
   <result name="success">/success.jsp</result>
</action>

3) Add the following JSPs to invoke the respective methods (functions) in the action class. By default, the execute() method is invoked.

userActions.jsp

<%@taglib uri="/struts-tags" prefix="s"%>

<html>
<body><s:form action="User">
   <s:submit />
   <s:submit action="addUser" value="Add User" />
   <s:submit action="updateUser" value="Update User" />
   <s:submit action="deleteUser" value="Delete User" />
</s:form>
</body>
</html>

success.jsp

<%@taglib uri="/struts-tags" prefix="s"%>

<html>
<body>
   <s:property value="message" />
</body>
</html>

4) Test the code with the following URL in the browser,

http://localhost:8080/WebAppName/userActions.jsp

No comments:

Post a Comment