In this tutorial you will learn about the Struts 2 Actions and its application with practical example.
Struts 2 Actions
Actions are the core component of Struts2 Web Application.When the user clicks on hyperlink or submit form action in Struts2 Web Application so the input is collected by the Controller and then Controller sends it to Java class which is called Actions. After the execution of Action the resources are selected to render the response. JSP, PDF , an Excel spreadsheet and a Java applet window are the resources which has been selected by the action. JSP is generally used as resources.
Each Url is mapped with a specific action, which is used to provides the processing logic which is necessary to service the request from the user.
Action Interface
Action interface provides us 5 Constant and one execute method, which are listed below
1 2 3 4 5 6 7 8 |
public interface Action { public static final String SUCCESS = "success"; public static final String NONE = "none"; public static final String ERROR = "error"; public static final String INPUT = "input"; public static final String LOGIN = "login"; public String execute() throws Exception; } |
SUCCESS:- This constant is used to indicates that action execution is successful and a success result shown to user.
NONE :- This constant is used to indicates that action execution is successful but no result shown to user.
ERROR :- This constant is used to indicates that the action execution is failed and error message should be displayed to user.
INPUT :- This constant is used to represent that the validation is failed.
LOGIN :- This constant is used to represent that the user is not logged-in.
execute() :- This is the only one method of this interface, should be implemented overridden by the action class.
See below code of Action class, we have used this in previous article.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
package example; public class HelloWorldAction { private String name; public String execute() throws Exception { return "success"; } public String getName() { return name; } public void setName(String name) { this.name = name; } } |
ActionSupport class: This class mostly used instead of Action because it is implemented by many interface such as Action, validateable, ValidationAware, TextProvider, LocaleProvider and Serializable.
Below is the code of Action Support class.
1 2 3 4 5 6 7 |
package example; import com.opensymphony.xwork2.ActionSupport; public class HelloWorldAction extends ActionSupport{ public String execute(){ return SUCCESS; } } |