Struts 2 Core Components

Struts 2 Core Components

In this article, I am going to discuss the Struts 2 Core Components. Please read our previous article where we discussed How to Create Struts 2 Application in MyEclipse. At the end of this article, you will understand the following pointers in detail.

  1. Struts 2 Interceptors
  2. Advantage of interceptors
  3. Struts 2 default interceptors
  4. Struts 2 ValueStack
  5. ValueStack Interface
  6. Methods of ValueStack interface
  7. Struts 2 ActionContext
  8. Struts 2 ActionInvocation
  9. ActionInvocation Interface
  10. Methods of ActionInvocation Interface
  11. Struts 2 OGNL
What is an Interceptor?

At the time of preprocessing and postprocessing of a request, the interceptor object is called. Many features are implemented in Struts 2 using interceptors such as – validation, exception handling, file uploading, etc.

How to use an Interceptor?

In our “Hello World” program we are using already existing interceptors. Those are –

  1. Timer interceptor – it will calculate the accurate time of execution of an action method.
  2. Params interceptor – it will send the request parameters to the action.

If you don’t use these interceptors, then you will encounter the problem that stating name property is not set because the parameter is unable to reach the action.

In the previous chapter, we built an application. The files which are used there (HelloWorldAction.java, web.xml, HelloWorld.jsp, and index.jsp), among them we will modify only the struts.xml file to add an interceptor.

<?xml version = "1.0" Encoding = "UTF-8"?>
<!DOCTYPE struts PUBLIC
   "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
   "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
   <constant name = "struts.devMode" value = "true" />
   
   <package name = "helloworld" extends = "struts-default">
      <action name = "hello" 
         class = "com.info.struts2.HelloWorldAction"
         method = "execute">
         <interceptor-ref name = "params"/>
         <interceptor-ref name = "timer" />
         <result name = "success">/HelloWorld.jsp</result>
      </action>
   </package>
</struts>

To create a War file right click on the project name and go to Export -> WAR File. In the Tomcat’s webapps directory deploy that WAR file. Now start the Tomcat server and access the URL http://localhost:8080/HelloWorldStruts2/index.jsp.It will display the following screen.

Struts 2 Core Components

Enter any word as per your choice in the blank text box and click on the Say Hello button to execute the defined action. The log is generated and you will find the below text –

INFO: Server startup in 3539 ms
27/08/2011 8:40:53 PM
com.opensymphony.xwork2.util.logging.commons.CommonsLogger info
INFO: Executed action [//hello!execute] took 109 ms.

Advantages of Interceptors

To delete any concern like validation, exception handling, logging, etc. from the application, there is no need for the redeployment of the application, what we need to do is that just eliminate the entry from the struts.xml file.

Struts 2 Default Interceptors
  1. alias – converts similar types of parameters that have disparate names between requests.
  2. chain – makes the properties of preceding action that are available in the current action and also used with chain result type.
  3. checkbox – used to handle the checkboxes in the sequence manner. And through this, we can easily identify the unchecked checkboxes.
  4. cookie – used to add a cookie to the current action.
  5. conversionError – used to add conversion errors to the action’s field errors.
  6. createSession – used to create the HttpSession object if it doesn’t exist.
  7. clearSession – releases the HttpSession object.
  8. debugging – used to provide support for debugging.
  9. execAndWait – used to send an intervening waiting page for the result.
  10. exception – used to guide an exception to a result.
  11. fileUpload – used to provide support to file upload in struts 2.
  12. i18n – used to provide support to internationalization and localization.
  13. jsonValidation – provides support to asynchronous support.
  14. logger – used to find out the action name.
  15. store – used to store and repossess action messages, action errors for action that implements the ValidationAware interface.
  16. modelDriven – used to make other model objects as the default object of valuestack.
  17. scopedModelDriven – same as ModelDriven but works only for action that implements ScopedModelDriven.
  18. params – colonizes the action properties with the request parameters.
  19. prepare – used to perform preparation logic if action implements a Preparable interface.
  20. profiling – used to support action profiling.
  21. roles – used to support role-based action.
  22. scope – used to store the action state in the session or application scope.
  23. servletConfig – used to provide access to maps that represent HttpServletRequest and HttpServletResponse.
  24. staticParams – pointing the static properties to action properties.
  25. timer – gives the output to the time that needed to execute an action.
  26. token – prevents imitation submission of the request.
  27. tokenSession – prevents imitation submission of the request.
  28. validation – used to provide support to input validation.
  29. workflow – can call the validate method of action class if any action class implements Validateable interface.
Struts 2 ValueStack

A Value Stack is simply a stack that contains application-specific objects such as Action object, Model object, Named objects, and Temporary objects. Though the action is placed at the top of the stack during the execution time.

ValueStack Interface

To deal with valuestack an interface is provided by the Struts framework. It consists of many useful methods.

Methods of ValueStack Interface

findValue(String expr): To find a value for a specific expression
Syntax: public Object findValue(String expr)

findString(String expr): To find a string for a specified expression.
Syntax: public String findString(String expr)

peek(): It returns the object which is at the top of the stack without removing it
Syntax: public Object peek()

pop(): It returns the object which is at the top of the stack and removes it from the stack
Syntax: public Object pop()

push(Object o): On the top of the stack it put the particular object.
Syntax: public void push(Object o)

set(String key, Object value): Sets an object on the stack with the specified key, which can be retrieved using findValue(key).
Syntax: public void set(String key, Object value)

size(): It gives the no. of objects in the stack.
Syntax: public int size()

What is ActionContext?

It is basically a container that stores the objects that are related to the current request-response of a web application. When a session or application or locale etc is going on it is created during a complete client-server interaction.

The objects are stored in a particular manner such as Temporary Objects -> Model Object -> Action Object -> Named Object. All the objects of ValueStack and also other objects that are relatable to the current interaction of web applications to the client.

What is ActionContext?

The context map of an ActionContext has the following objects –

  1. Application
  2. Session
  3. ValueStack
  4. Action
  5. Request
  6. Parameters
  7. Attr

To make our ActionContext thread-safe, in every context the object that is stored is distinguishable. Thus, we don’t need to declare the objects as synchronized.

We can refer the current ActionContext by calling the getContext() method of the ActionContext class. Hence, for referring the current ActionContext the following method is used:

ActionContext context = ActionContext.getContext();
// to access objects from ValueStack we should use:
ActionContext context = ActionContext.getContext().getValueStack();

Syntax: public class ActionContext extends Object implements Serializable

ActionContext Methods:

ActionContext Methods

ActionInvocation

It represents the execution state of an activity. The action and interceptor objects are in hold of it.

Syntax: public interface ActionInvocation extends Serializable

ActionInvocation Interface

An ActionInvocation Interface is provided by the struts framework to deal with the ActionInvocation. It has many methods, among them some help to get the instance of ActionProxy, ActionContext, ValueStack, Result, etc.

Methods of ActionInvocation Interface

Methods of ActionInvocation Interface

What is OGNL?

Object Graph Navigational Language (OGNL) is an open-source framework used to get properties from Java Beans. In Struts 2 –

  1. It is used to reference and manipulate data on the ValueStack.
  2. performs two important tasks – data transfer and type conversion.
What are the features of OGNL?
  1. type conversion
  2. calling methods
  3. collection manipulation and generation
  4. projection across collections
  5. expression evaluation
  6. lambda expressions

Syntax: Accessing the action property
<s:property value=”propertyName”/>
Syntax: Accessing the property from a scope (request, session or application)
<s:property name=”#scopeName. propertyName “/>

OGNL Example

test.jsp
<%@ taglib uri="/struts-tags" prefix="s"%>
<html>
 <head>
  <title>Struts 2 OGNL example</title>
 </head>
 <body>
  <h3>This is a OGNL example.</h3>	 
  <h4><a href="welcome">Click here </a>
           to see the list values by using OGNL.</h4>	 
 </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="user" extends="struts-default">
  <action name="welcome" 
             class="com.info.action.Test">
   <result name="success">/welcome.jsp</result>
  </action>
 </package> 
</struts>
Test.java
import java.util.ArrayList;
import java.util.List;

public class Test
{
    //data members
    private List < String > myList = new ArrayList < String > ();
    
    //business logic
    public String execute ()
    {
        myList.add ("Bharat");
        myList.add ("Richi");
        myList.add ("Sahdev");
        myList.add ("Rajesh");
        myList.add ("Himanshu");
        myList.add ("Vivek");
        myList.add ("Shveta");
        myList.add ("Bharti");
        return "success";
    }
    public List < String > getMyList ()
    {
        return myList;
    }
    public void setMyList (List < String > myList)
    {
        this.myList = myList;
    }
}
welcome.jsp
<%@ taglib uri="/struts-tags" prefix="s"%>
<html>
 <head>	
     <title>Struts 2 OGNL example</title>
 </head>
 <body>
 <h3>This is a OGNL example.</h3>
 <h5> All list items: <s:property value="myList" /> </h5>
 <h5> Second list item: <s:property value="myList[1]" /> </h5>
 <h5> List size: <s:property value="myList.size" /> </h5>
 </body>
</html>

Output:

OGNL Example

Once you click on the Click here link, you will get the following output.

Struts 2 Core Components

In the next article, I am going to discuss the Struts 2 Action Interface. Here, in this article, I try to explain the Struts 2 Core Components and I hope you enjoy this Struts 2 Core Components article.

Leave a Reply

Your email address will not be published. Required fields are marked *