Struts2

The ValueStack in Struts 2

In this tutorial we will discuss about the ValueStack in the Struts2 how its work behind the scene. Fist lets see the high level picture of flow request data to Struts2 framework.

Step 1. Client send the request to server.
Step 2. Struts configuration file map to specific action class.
Step 3. Action class has business service class to operate business logic and return result data to the action class and action class set this data to self member variables.
Step 4. After setting result to member variable it send to the JSP to view.
Step 5. JSP using the some TAGS to display result.
Step 6. JSP prepare the response as HTML and return to client.

Now we will see the How Servlet work. High Level flow of request to Servlet.

Step-
1.  We are given objects to use, but we will need to do the “push” and “pull” of data ourseleves.
2. Servlet places the business data into the session and the JSP accesses it.
3 This has to be done for every servlet-to-JSP flow that data to be communicated.

Now we move to Struts2 framework how it is work internally.
Step 1. New Action objects are created for each request.

In the above every requests have own Action instances with member variables. Now here there are some complicated to display member variable to JSP. it may be override to each other. So overcome this problem Struts 2 introduce to ValueStack.

ValueStack-

A valueStack is simply a stack that contains application specific objects such as action objects and other model object. At the execution time, action is placed on the top of the stack. We can put objects in the valuestack, query it and delete it.

1. It is not really a stack in the traditional sense.
2. It does stack up objects.
3. Behave like a virtual object.
4. Makes it easy to refer to member variables.

The value stack is a set of several objects which keeps the following objects in the provided order:
SN Objects & Description
1 Temporary Objects
There are various temporary objects which are created during execution of a page. For example the current iteration value for a collection being looped over in a JSP tag.
2 The Model Object
If you are using model objects in your struts application, the current model object is placed before the action on the value stack
3 The Action Object
This will be the current action object which is being executed.
4 Named Objects
These objects include #application, #session, #request, #attr and #parameters and refer to the corresponding servlet scopes
The value stack can be accessed via the tags provided for JSP, Velocity or Freemarker. There are various tags which we will study in separate chapters, are used to get and set struts 2.0 value stack. You can get valueStack object inside your action as follows:
ActionContext.getContext().getValueStack()
Once you have a ValueStack object, you can use following methods to manipulate that object:
SN ValueStack Methods & Description
1 Object findValue(String expr)
Find a value by evaluating the given expression against the stack in the default search order.
2 CompoundRoot getRoot()
Get the CompoundRoot which holds the objects pushed onto the stack.
3 Object peek()
Get the object on the top of the stack without changing the stack.
4 Object pop()
Get the object on the top of the stack and remove it from the stack.
5 void push(Object o)
Put this object onto the top of the stack.
6 void set(String key, Object o)
Sets an object on the stack with the given key so it is retrievable by findValue(key,…)
7 void setDefaultType(Class defaultType)
Sets the default type to convert to if no type is provided when getting a value.
8 void setValue(String expr, Object value)
Attempts to set a property on a bean in the stack with the given expression using the default search order.
9 int size()
Get the number of objects in the stack.

The OGNL:

The Object-Graph Navigation Language (OGNL) is a powerful expression language that is used to reference and manipulate data on the ValueStack. OGNL also helps in data transfer and type conversion.
The OGNL is very similar to the JSP Expression Language. OGNL is based on the idea of having a root or default object within the context. The properties of the default or root object can be referenced using the markup notation, which is the pound symbol.
As mentioned earlier, OGNL is based on a context and Struts builds an ActionContext map for use with OGNL. The ActionContext map consists of the following:
  • application – application scoped variables
  • session – session scoped variables
  • root / value stack – all your action variables are stored here
  • request – request scoped variables
  • parameters – request parameters
  • atributes – the attributes stored in page, request, session and application scope
It is important to understand that the Action object is always available in the value stack. So, therefore if your Action object has properties x and y there are readily available for you to use.
Objects in the ActionContext are referred using the pound symbol, however, the objects in the value stack can be directly referenced, for example if employee is a property of an action class then it can get referenced as follows:
<s:property value="name"/>

instead of

<s:property value="#name"/>

If you have an attribute in session called “login” you can retrieve it as follows:

<s:property value="#session.login"/>

OGNL also supports dealing with collections – namely Map, List and Set. For example to display a dropdown list of colors, you could do:

<s:property name="color" list="{'red','yellow','green'}"/>

ValueStack/OGNL Example:-

CREATE ACTION:

Let us consider following action class where we are accessing valueStack and then setting few keys which we will access using OGNL in our view ie. JSP page.

package com.dineshonjava.struts2.action;

import java.util.HashMap;
import java.util.Map;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.util.ValueStack;

/**
 * @author Dinesh Rajput
 *
 */
public class HelloWorldAction extends ActionSupport {
 private static final long serialVersionUID = 4956157388836635122L;
 private String name;

    public String execute() throws Exception {
       ValueStack stack = ActionContext.getContext().getValueStack();
       Map<String, Object> context = new HashMap<String, Object>();

       context.put("key1", new String("This is key1")); 
       context.put("key2", new String("This is key2"));
       stack.push(context);

       System.out.println("Size of the valueStack: " + stack.size());
       return "success";
    }  

    public String getName() {
       return name;
    }

    public void setName(String name) {
       this.name = name;
    }
}

Actually, Struts 2 adds your action to the top of the valueStack when executed. So, the usual way to put stuff on the Value Stack is to add getters/setters for the values to your Action class and then use <s:property> tag to access the values. But I’m showing you how exactly ActionContext and ValueStack work in struts.

CREATE VIEWS

Let us create the below jsp files success.jsp in the WebRoot folder in your eclipse project. This view will be displayed in case action returns success:

<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<title>Hello World</title>
</head>
<body>
   Entered value : <s:property value="name"/><br/>
   Value of key 1 : <s:property value="key1" /><br/>
   Value of key 2 : <s:property value="key2" /> <br/>
</body>
</html>

We also need to create index.jsp in the WebRoot folder whose content is as follows:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
   pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
   <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Hello World</title>
</head>
<body>
   <h1>Hello World From Struts2</h1>
   <form action="hello">
      <label for="name">Please enter your name</label><br/>
      <input type="text" name="name"/>
      <input type="submit" value="Say Hello"/>
   </form>
</body>
</html>

CONFIGURATION FILES

Following is the content of struts.xml file:

<?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.dineshonjava.struts2.action.HelloWorldAction" method="execute">
         <result name="success">/success.jsp</result>
      </action>
   </package>
 </struts>

Following is the content of web.xml file:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>Struts2ValueStack</display-name>
  <filter>
        <filter-name>struts2</filter-name>
        <filter-class>
            org.apache.struts2.dispatcher.FilterDispatcher
        </filter-class>
    </filter>
    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>

Right click on the project name and click Export > WAR File to create a War file. Then deploy this WAR in the Tomcat’s webapps directory. Finally, start Tomcat server and try to access
URL http://localhost:8080/doj/. This will give you following screen:

Now enter any word in the given text box and click “Say Hello” button to execute the defined action. Now if you will check the log generated, you will find following text at the bottom:

output on console:
Size of the valueStack: 3

and this will display following screen, which will display whatever value you will enter and value of key1 and key2 which we had put on ValueStack.

 

Download SourceCode + Libs
Struts2ValueStack.zip

 

<<Previous <<   || Index ||   >>Next >>
Previous
Next
Dinesh Rajput

Dinesh Rajput is the chief editor of a website Dineshonjava, a technical blog dedicated to the Spring and Java technologies. It has a series of articles related to Java technologies. Dinesh has been a Spring enthusiast since 2008 and is a Pivotal Certified Spring Professional, an author of a book Spring 5 Design Pattern, and a blogger. He has more than 10 years of experience with different aspects of Spring and Java design and development. His core expertise lies in the latest version of Spring Framework, Spring Boot, Spring Security, creating REST APIs, Microservice Architecture, Reactive Pattern, Spring AOP, Design Patterns, Struts, Hibernate, Web Services, Spring Batch, Cassandra, MongoDB, and Web Application Design and Architecture. He is currently working as a technology manager at a leading product and web development company. He worked as a developer and tech lead at the Bennett, Coleman & Co. Ltd and was the first developer in his previous company, Paytm. Dinesh is passionate about the latest Java technologies and loves to write technical blogs related to it. He is a very active member of the Java and Spring community on different forums. When it comes to the Spring Framework and Java, Dinesh tops the list!

Share
Published by
Dinesh Rajput

Recent Posts

Strategy Design Patterns using Lambda

Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…

2 years ago

Decorator Pattern using Lambda

Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…

2 years ago

Delegating pattern using lambda

Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…

2 years ago

Spring Vs Django- Know The Difference Between The Two

Technology has emerged a lot in the last decade, and now we have artificial intelligence;…

2 years ago

TOP 20 MongoDB INTERVIEW QUESTIONS 2022

Managing a database is becoming increasingly complex now due to the vast amount of data…

2 years ago

Scheduler @Scheduled Annotation Spring Boot

Overview In this article, we will explore Spring Scheduler how we could use it by…

3 years ago