Actions in Struts2

The action classes are core concepts in Struts2; it is Model class itself and contains the business logic for processing on the data. Action classes act as controller in the MVC (Model View Controller) pattern. So actions are the core part of Struts2 framework. The main functionalities of action classes is respond to a user request, execute business logic, and then return a result to the user based on configuration file (struts.xml) to render the view page.

Stuts2 actions are not singleton, means instance of action is created on each request. Hence Struts2 action need not be thread safe like Struts1 actions. The action classes are simple and do not dependent on other API. So testing of action classes are much more easier.

There are three way to create actions in Struts2 :
Action class by extending ActionSupport class : Action classes usually extend the ActionSupport class, which is provided by the Struts 2 framework and provides most common functionalities of web application like ; validate data, action level message, action level error message, field level error message and read resource bundled.
package  techmyguru.actions;
import  com.opensymphony.xwork2.ActionSupport;
public class  EmployeeAction1 extends  ActionSupport 
{  
  @Override
  public  String execute() throws  Exception {
    return  SUCCESS;
  }
}

Action class by implementing Action interface :
All Struts2 actions may implement this interface, which exposes the execute() method.
package  techmyguru.actions;
import  com.opensymphony.xwork2.Action;
public class  EmployeeAction2 implements  Action 
{
  @Override
  public  String execute() throws  Exception {
    return  SUCCESS;
  }
}

Action class as POJO class :
The Struts2 also supports action class as POJO. You are free to define any entry level method other than execute(), but you have to configure it in struts.xml file. By default Struts2 framework call execute() method from POJO action class.
package  techmyguru.actions;
public class  EmployeeAction3 {
  public  String execute() throws  Exception {
  return  "success";
  }
}

Let's see the various classes and interfaces, which are used for creating, configuration and executing action classes

com.opensymphony.xwork2.ActionSupport class
It provides default action implementations for various services required by common action classes in Struts2. It implements Action, Validateable, ValidationAware, TextProvider, LocaleProvider, Serializable interfaces and provides all the functionalities by implementing methods.

com.opensymphony.xwork2.Action Interface
It is core interface for action classes. All actions may implement this interface, which override the execute() method. It is 5 static variables and a method.
Filed NameDescription
static String ERROR="error" The action execution was a failure
static String INPUT="input" The action execution require more input in order to succeed
static String LOGIN="login" The action could not execute, since the user most was not logged in
static String NONE="none" The action execution was successful but do not show a view
static String SUCCESS="success" The action execution was successful

com.opensymphony.xwork2.LocalProvider interface
This interface provides a single method Locale getLocale() to get localized message with the help of TextProvider interface.

com.opensymphony.xwork2.TextProvider interface
This interface provides methods to read localized message from resource bundle. Below are common methods :
Method Name Description
String getText(String key) Gets a message based on a message key, or null if no message is found
String getText(String key, String defaultValue) Gets a message based on a key, or, if the message is not found, a supplied default value is returned
ResourceBundle getTexts() Get the resource bundle associated with the implementing class (usually an action)
ResourceBundle getTexts(String bundleName) Get the named bundle, such as "pkg1/techmyguru/actions"
boolean hasKey(String key) Checks if a message key exists

com.opensymphony.xwork2.Validateable
This interface provides a single method void validate(). It executes before the business logic ex- execute() method from action class.

com.opensymphony.xwork2.ValidationAware<
This interface provides to add and retrieve action level or field level errors and action level messages also. Below are common methods to be used in the application:
Methods Description
void addActionError(String anErrorMessage) Add an Action-level error message to this Action
void addActionMessage(String aMessage) Add an Action-level message to this Action
void addFieldError(String fieldName, String errorMessage) Add an error message for a given field
void setActionErrors(Collection<String> errorMessages) Set the Collection of Action-level String error messages
void setActionMessages(Collection<String> messages) Set the Collection of Action-level String messages (not errors)
void setFieldErrors(Map<String,List<String>> errorMap) Set the field error map of fieldname (String) to Collection of String error messages

Let's create web application; which demonstrates the action classes.
Step 1: Create Dynamic Web Project with Struts configuration as below :
Dynamic web project for Struts2 action


Step 2: Edit deployment descriptor web.xml. [ Click here If you are not familiar with Struts 2 application environment setup in Eclipse. ]

Step 3: Copy the required jar files in WEB-INF\lib folder -
commons-collections-3.1.jar
commons-digester-2.0.jar
commons-fileupload-1.2.2.jar
commons-io-2.0.1.jar
commons-lang3-3.1.jar
commons-logging-1.1.1.jar
commons-logging-api-1.1.jar
freemarker-2.3.19.jar
javassist-3.11.0.GA.jar
ognl-3.0.6.jar
struts2-core-2.3.8.jar
xwork-core-2.3.8.jar

Step 4: Create input page Employee registration WebContent\index.jsp :
<%@taglib uri="/struts-tags" prefix="s"%>
<html>
<head>
<title>Employee Registration Page</title>
</head>
<body>
<h1>Employee Registration Form</h1>
  <s:form action="EmployeeAction1" method="post">
  <s:textfield label="Enter Code" name="code"/>
  <s:textfield label="Enter Name" name="name"/>
  <s:textfield label="Enter City" name="city"/>
  <s:textfield label="Enter Salary" name="salary"/>
  <s:submit label="Submit"/>
  <s:reset label="Reset"/>
  </s:form>
</body>
</html>

Step 5: Create action class by extending ActionSupport class :
The action class is created by extending ActionSupport class; it provides all the common functionalities. Hence it is recommended that action class based on ActionSupport class.
package techmyguru.actions;
import com.opensymphony.xwork2.ActionSupport;
public class EmployeeAction1 extends ActionSupport {
  private String code;
  private String name;
  private String city;
  private String salary;
        // all getter and setter methods
  @Override
  public String execute() throws Exception {
    System.out.println("Execute method in EmployeeAction1");
    return SUCCESS;
  }
}

Create action class by implementing Action interface :
If Action class created by implementing Action interface then no other features can be used; like- validation data in action, read Resource Bundled etc.
package techmyguru.actions;
import com.opensymphony.xwork2.ActionSupport;
public class EmployeeAction2 implements Action {
  private String code;
  private String name;
  private String city;
  private String salary;
        // all getter and setter methods
  @Override
  public String execute() throws Exception {
    System.out.println("Execute method in EmployeeAction1");
    return SUCCESS;
  }
}

Create action class as POJO class
By default framework search the execute method in action class; if action class has other than execute method then it has to be specify in the struts.xml file.
package techmyguru.actions;
import com.opensymphony.xwork2.ActionSupport;
public class EmployeeAction3 {
  private String code;
  private String name;
  private String city;
  private String salary;
        // all getter and setter methods
  @Override
  public String execute() throws Exception {
    System.out.println("Execute method in EmployeeAction1");
    return SUCCESS;
  }
}

Step 6: Create src\struts.xml :
The action tags has many attributes, but three are most common, name is mandatory " name of the action which is requested by the client, class " fully qualified Action class name if any, method- if action class has different method name other than execute(), then method name has to be mapped in struts.xml.
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
    "http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<package name="default" extends="struts-default">
  <action name="EmployeeAction1" class="techmyguru.actions.EmployeeAction1">
    <result name="success">/pages/EmployeeSuucess.jsp</result>
    <result name="input">/index.jsp</result>
  </action>
  <action name="EmployeeAction2" class="techmyguru.actions.EmployeeAction2">
    <result name="success">/pages/EmployeeSuucess.jsp</result>
    <result name="input">/index.jsp</result>
  </action>
  <action name="EmployeeAction3" class="techmyguru.actions.EmployeeAction3">
    <result name="success">/pages/EmployeeSuucess.jsp</result>
    <result name="input">/index.jsp</result>
  </action>
</package>
</struts>

Step 7: Create view component page EmployeeSuccess.jsp :
The OGNL expression language is in build feature in Struts2. It is used to get the value from ValueStack by putting property name in the property tag.
<%@taglib uri="/struts-tags" prefix="s"%>
<html>
<head>
<title>Employee Suucess Page</title>
</head>
<body>
<h1>Employee details are<br>
Employee Code :<s:property value="code"/><br>
Employee Name :<s:property value="name"/><br>
Employee City :<s:property value="city"/><br>
Employee Salary :<s:property value="salary"/><br>
<a href="index.jsp"> Try Agaian</a>
</h1>
</body>
</html>

Step 8: Run the application and see the output:
Struts 2 actions output

Step 9: Click submit and see get output:
Struts 2 actions output

Previous Download Source Code Next

Comment by : Venu GT January 29th, 2015
Comment : Very very nice


Write your Comment

Name :
Email Id : [ We will not publish your email id ]
Your Comment : [ Maximum 200 chars ]
Enter Security code