Struts 2 push tag example

Struts 2 “push” tag is used to push value to the top of stack, so that it can be access or reference easily. See a complete “push” tag example :

1. Action

Action class to forward the request only.

PushTagAction.java


package com.mkyong.common.action;

import com.opensymphony.xwork2.ActionSupport;
 
public class PushTagAction extends ActionSupport{

	public String execute() throws Exception {
		
		return SUCCESS;
	}
}

2. Bean

A simple Person class, later will push it into the stack for easy access.

Person.java


package com.mkyong.common;

public class Person{

	private String firstName = "This is firstName";
	private String lastName = "This is lastName";
	
	public String getFirstName() {
		return firstName;
	}
	public String getLastName() {
		return lastName;
	}
}

3. push tag example

It shows the use of “push” tag.

push.jsp


<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
</head>
 
<body>
<h1>Struts 2 push tag example</h1>

<h2>1. Normal way</h2>
<s:bean name="com.mkyong.common.Person" var="personBean" />
First name : <s:property value="#personBean.firstName" /><br/>
Last name: <s:property value="#personBean.lastName" /><br/>

<h2>2. Push way</h2>
<s:push value="#personBean" >
First name : <s:property value="firstName" /><br/>
Last name: <s:property value="lastName" /><br/>
</s:push>

</body>
</html>

How it work?
Normally, if you want to get the bean’s property, you may reference it like <s:property value=”#personBean.firstName” />. With “push” tag, you can push the “#personBean” to the top of the stack, and access the property directly <s:property value=”firstName” />. Both are returned the same result, but with different access mechanism only.

The “push” tag is saving you to type few characters, don’t see any real value behind.

4. struts.xml

Link it ~


<?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="default" namespace="/" extends="struts-default">
	
		<action name="pushTagAction" 
			class="com.mkyong.common.action.PushTagAction" >
			<result name="success">pages/push.jsp</result>
		</action>
		
	</package>
</struts>

5. Demo

http://localhost:8080/Struts2Example/pushTagAction.action

Output

Struts 2 push tag example

Reference

  1. Struts 2 push tag documentation

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

avatar
0 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
0 Comment authors
Recent comment authors
newest oldest most voted