Struts 2 basics - Java

Struts 2 developers have identified all these modules and had builded the same. Below is how a struts 2 design will look like.
 
Struts 2 high level framework architecture
 
Here Interceptor is the gate way through which a request is passed. It takes care of getting user request parameters,
 
Struts 2 framework get all the request parameters from interceptor and makes it available for Action class and we don’t need to fetch it in the action class via any request or session objects like we do in Servlets, because struts 2 makes it available.
 
Here Struts.xml acts as controller which Controls the execution flow of the request, Action class represents Model and JSP represent View layer.
 
Note:
 
In struts 2 the data can be displayed in jsp with tab library,

Types of Actions class in Struts 2


Action class in Struts 2

The functionality of the action class is to retrieve resource bundle, hold the data, provide validation, perform business logic and select the view result page that should be sent back to the user.

Request Processing Life Cycle Workflow in Struts 2
There are four different ways to write struts 2 action class , which are as follows
 

1. Action


For Struts 2 actions, it is not mandatory to implement any interface or extend any class. It is only required to implementexecute() method that returns a string which is to be used in struts.xml, to indicate the result page that has to be rendered(return)

** UPDATE: Struts 2 Complete tutorial now available here.
 
package com.action;
public class LoginAction
{
     public String execute() 
     {          
     return "success";
     }
}

In the struts.xml, configure the action class with action tag and class attribute. Define which result page should be returned to the user with result tag and the name of the action you can use to access this action class with name attribute.
 
<package name="default" extends="struts-default">
  <action name="login" class="com.action.LoginAction">
      <result name="success">success.jsp</result>
  </action>
<package>

Now you can access the action via
http://localhost:8089/StrutsLogin/login
Note : To change the extension to any value that suits your need, view – Struts2 Custom extension example.

 

2. Action interface


The second way of creating Action class on Struts 2 is to implement an optional action interface (com.opensymphony.xwork2.Action).

This interface , comes with 5 common used constant values : success, error, none, input and logic. By implements this interface, the action class can use the constant value directly.

The Source code for Action interface :
package com.opensymphony.xwork2;
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;
}

Example: Struts 2 Action class implementing Action interface
 
package com.action;
import com.opensymphony.xwork2.Action;
public class LoginAction implements Action
{
    public String execute() 
    {
        return SUCCESS;
    }
}

3. ActionSupport


The third way of creating Action class on Struts 2 is to extend the ActionSupport class (com.opensymphony.xwork2.ActionSupport). The ActionSupport class is a very powerful and convenient class that provides default implementation of few of the important interfaces :
 
public class ActionSupport implements Action, Validateable, 
   ValidationAware, TextProvider, LocaleProvider, Serializable {
 ...
}
 
Note:
Instead of implementing Action interface, it is better to extend the ActionSupport, Since the ActionSupport class implements Action interface along with other useful interfaces.

 
The ActionSupport class give you the ability to do :
1. Validation Declare a validate() method and put the validation code inside.
2. Text localization Use GetText() method to get the message from resource bundle.
 
LoginAction.properties, (The resource bundle name must be same as Action class name with the extension .properties), and should be in the same folder where the action class lies
 
Note :
We will get to know about what is property file and the use of addFiendError , and use of other functionality like addActionError and addActionMessage in our upcoming tutorials.

 
Example: Struts 2 Action class extending ActionSupport class
 
package com.action;
import com.opensymphony.xwork2.ActionSupport;
public class LoginAction extends ActionSupport {
private static final long serialVersionUID = 6677091252031583948L;
private String userName;
public String execute() 
       {
        return SUCCESS;
       }

        public String getUserName() 
        {
                return userName;
        }

        public void setUserName(String userName) 
        {
                this.userName = userName;
        }

        public void validate()
        {
           if (!userName.isEmpty()) 
           {
           addFieldError("userName", getText("username.required"));
           }
       }
}

** UPDATE: Android Complete tutorial now available here.
 

4. Action annotation


Struts 2 has very good support for annotations, you can get rid of the XML file and replace with @action in your action class.
 
package com.simplecode.action;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.ResultPath;
import com.opensymphony.xwork2.ActionSupport;
@ResultPath(value="/")
public class LoginAction extends ActionSupport
{ @Action(value="login", results={@Result(name="success", location="success.jsp")})
        public String execute() 
        {
        return SUCCESS;
        }
}


Execution flow of struts2    The flow starts with the web browser placing a request for a particular resource. This request is received by the web container. The container loads web.xml and checks if the url patterns match. If it matches, the web container transfers the request to Filter Dispatcher.
The Filter Dispatcher decides the suitable action , by calling the ActionMapper , which in turn calls the ActionProxy. ActionProxy reads the configuration file such as struts.xml, and finds the suitable action for the request. ActionProxy creates an instance of ActionInvocation class. The ActionInvocation class invokes the Interceptors one by one (if required).   Do Read
  • Concept of Interceptors in Struts 2
  •   The Interceptors use the required functions and after that, the Action method executes all the functions like storing and retrieving data from a database. ActionInvocation receives the final result produced by an action class.
    Once the Action returns, the ActionInvocation is responsible for looking up the proper result associated with the Action result code mapped in struts.xml. The Interceptors are executed again in reverse order and the response is returned from ActionProxy to the Filter (In most cases to FilterDispatcher). FilterDispatcher selects an appropriate view, basing on the result. The result is then sent to the servlet container which in turn sends it back to the client. Then the result can be seen on the output of the browser in HTML, PDF, images or any other format.
    The other important features of Struts 2 are ValueStack & OGNL. Object-Graph Navigation Language (OGNL) is a powerful expression language that is used to reference and manipulate data on the ValueStack. OGNL expression language provides simplified syntax to reference java objects. It helps in data transfer and type conversion by binding the java-side data properties to the string-based view layer.   Action context   ** UPDATE: Struts 2 Complete tutorial now available here.   In Struts 2 the action resides on the ValueStack which is a part of the ActionContext. ActionContext is a global storage area that holds all the data associated with the processing of a request.
    When a request comes the param interceptor helps in moving the request data to the ValueStack. Now the OGNL does the job of converting the string based form data to their corresponding java types. OGNL does this by using the set of availablebuilt-in type converters.
    Again when the results are generated the OGNL converts the java types of the property on the ValueStack to the string-based HTML output.Here for N number of request N number of object is created, this makes the Struts 2 actions thread safe.

    Comments

    Popular posts from this blog

    EJB - Stateful vs Stateless

    Inversion of Control vs Dependency Injection