Struts 2 Data Tags Example Tutorial

In last article we saw how we can use OGNL in Struts 2 to work with application data and store or retrieve it from ValueStack. Struts 2 provide a lot of custom tags that we can use in JSP pages to get the application data from ValueStack as well as from request, session or application scope attributes.

Struts 2 tags can be divided into three categories – Data tags, Control tags and UI tags. Today we will look into Struts2 Data tags and how we can use them in JSP pages. We need to import Struts 2 tag libraries in JSP pages to use them through taglib directive as:

<%@ taglib uri="/struts-tags" prefix="s" %>

Let’s first have the brief introduction of the Struts 2 Data tags and then we will look at their usage in a struts project.

  1. property tag: This is one of the most widely used tag to get the property from ValueStack as well as application, session or request scopes. Some of the important attributes of property tag are – value for expression, default for default value if OGNL expression returns null and escapeHtml for escaping HTML tags. We can also invoke a bean method through property tag.
    <s:property value="country" default="USA"/>
    
  2. set tag: This is used to set values in application, session, request, page, or action. If we don’t provide any scope, value will be set for action.
    <s:set var="defaultGender" value="gender" scope="application"></s:set>
    
  3. push tag: Most of the times in result pages, we work with bean properties from a single bean. We can use push tag to pus the value on top of the stack, so that we can use the properties directly without prefixing it with bean. This helps in writing cleaner code when single bean is used a lot.
    <s:push value="user">
    User Name = <s:property value="name" /><br> <!-- no need to use user.name now -->
    </s:push>
    
  4. bean tag: We can use bean tag to initialize a java bean in JSP page and then use param tag to pass parameters to it’s properties setter methods. Once the bean is initialized, we can access it with property tag.
    <s:bean name="com.journaldev.struts2.model.User" var="myUser">
    	<s:param name="name">Pankaj</s:param>
    </s:bean>
    
  5. action tag: We can use action tag to invoke another action from result pages and then use the returned value in the page. We can choose to render the response in current page through executeResult attribute.
    <s:action name="footer" namespace="/" executeResult="true"></s:action>
    
  6. a tag: We can use this tag to create hyperlinks in the JSP page.
    <s:a href="http://www.journaldev.com">Go To Home</s:a>
    
  7. date tag: We can use this tag to get java bean date variable and then format it with formatter.
    <s:date name="date" format="MM/dd/yyyy"/>
    
  8. include tag: This is similar to JSP include action and we can use it to include another resource in the JSP page.
    <s:include value="/footer.jsp"></s:include>
    
  9. i18n and text tag: These tags can be used for i18n support in JSP pages. We can use i18n tag to provide the property file name where we should look for the key value, key name is passed with text tag.
    <s:i18n name="global">
        <s:text name="home.name"></s:text>
    </s:i18n>
    
  10. debug tag: We can use this tag for debugging JSP pages. This tag creates a Debug link that shows us ValueStack contents and stack context information.
    <s:debug></s:debug>
    

We will create a simple web application where we will use above tags in JSP result page. We will create simple action classes to populate the bean values. We will also create global property file to be used for i18n. Our final project will look like below image.

Struts2-data-tags-example

Configuration Files

<?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" 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>Struts2DataTagsExample</display-name>

	<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>

</web-app>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>Struts2DataTagsExample</groupId>
	<artifactId>Struts2DataTagsExample</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>

	<dependencies>
		<dependency>
			<groupId>org.apache.struts</groupId>
			<artifactId>struts2-core</artifactId>
			<version>2.3.15.1</version>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.1</version>
				<configuration>
					<source>1.6</source>
					<target>1.6</target>
				</configuration>
			</plugin>
			<plugin>
				<artifactId>maven-war-plugin</artifactId>
				<version>2.3</version>
				<configuration>
					<warSourceDirectory>WebContent</warSourceDirectory>
					<failOnMissingWebXml>false</failOnMissingWebXml>
				</configuration>
			</plugin>
		</plugins>
		<finalName>${project.artifactId}</finalName>
	</build>
</project>

pom.xml and web.xml files have configuration for using Struts 2 in web application.

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE struts PUBLIC
	"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
	"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<constant name="struts.devMode" value="false"></constant>
<constant name="struts.convention.result.path" value="/"></constant>
<constant name="struts.custom.i18n.resources" value="global" />

<package name="user" namespace="/" extends="struts-default">
	<action name="home" class="com.journaldev.struts2.actions.HomeAction">
	<result name="success">/home.jsp</result>
	</action>

	<action name="footer" class="com.journaldev.struts2.actions.FooterAction">
	<result name="success">/footer.jsp</result>
	</action>
</package>

</struts>

The important point to note is the struts.custom.i18n.resources configuration to use global.properties file for i18n.

home.name=Home
home.title=Home Page

Simple property file that will be used in result page to show messages.

Java Bean Class

package com.journaldev.struts2.model;

import java.util.Date;

public class User {

	private String name;
	private String address;
	private String gender;
	private Date date;
	
	public User(){
		this.date = new Date();
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getAddress() {
		return address;
	}
	public void setAddress(String address) {
		this.address = address;
	}
	public String getGender() {
		return gender;
	}
	public void setGender(String gender) {
		this.gender = gender;
	}
	
	public String getDefaultName(){
		return "admin";
	}
	public Date getDate() {
		return date;
	}
	public void setDate(Date date) {
		this.date = date;
	}
}

Simple java bean whose values will be set in the action class and used in JSP page to show values.

Action Classes

package com.journaldev.struts2.actions;

import com.journaldev.struts2.model.User;
import com.opensymphony.xwork2.ActionSupport;

public class HomeAction extends ActionSupport {

	private static final long serialVersionUID = 1L;

	@Override
	public String execute(){
		user = new User();
		user.setName("Pankaj Kumar");
		user.setGender("Male");
		
		return SUCCESS;
	}
	
	private User user;

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	
}

Simple action class that is setting java bean properties.

package com.journaldev.struts2.actions;

import com.opensymphony.xwork2.ActionSupport;

public class FooterAction extends ActionSupport {

	@Override
	public String execute() {
		return SUCCESS;
	}
}

This action will be invoked from JSP page using action tag.

Result Pages

<strong>Footer Data</strong>

Simple HTML fragment that will be included in home.jsp using include tag and its the response of footer action.

<%@ page language="java" contentType="text/html; charset=US-ASCII"
    pageEncoding="US-ASCII"%>
<%@ taglib uri="/struts-tags" prefix="s" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Home Page</title>
</head>
<body>
<h4>Struts 2 property tag example</h4>

User Name = <s:property value="user.name"/><br>
User Address = <s:property value="user.address" default="USA"/><br>

<h4>Struts 2 set tag example</h4>
<s:set var="defaultGender" value="user.gender" scope="application"></s:set>
Default Gender = <s:property value="#application.defaultGender"/><br>
Default Gender = <s:property value="#application['defaultGender']"/><br>

<h4>Struts 2 push tag example</h4>
<s:push value="user">
User Name = <s:property value="name" /><br>
User Address = <s:property value="address" default="USA"/><br>
User Address = <s:property value="gender" default="female"/><br>
</s:push>

<h4>Struts 2 bean tag example</h4>
<s:bean name="com.journaldev.struts2.model.User" var="myUser">
	<s:param name="name">Lisa</s:param>
	<s:param name="gender" value="#application.defaultGender"></s:param>
	<s:param name="address">India</s:param>
</s:bean>

MyUser Name = <s:property value="#myUser.name"/><br>
MyUser Gender = <s:property value="#myUser.gender"/><br>
MyUser Address = <s:property value="#myUser.address"/><br>
Default Name = <s:property value="#myUser.getDefaultName()"/><br>

<h4>Struts 2 action tag example</h4>

Data from footer action = <s:action name="footer" namespace="/" executeResult="true"></s:action>

<h4>Struts 2 Miscellaneous Data tags example</h4>

a tag example: <s:a href="#top">Go To Top</s:a><br>
date tag example: <s:date name="user.date" format="MM/dd/yyyy"/><br>
include tag example: <s:include value="/footer.jsp"></s:include><br>
text tag example: <s:text name="home.title"></s:text><br>
i18n tag example: <s:i18n name="global"><s:text name="home.name"></s:text></s:i18n><br>
debug tag example: <s:debug></s:debug>

</body>
</html>

This is the main result page where all the Struts 2 data tags usage are shown. Please look into this carefully for example usage of struts 2 data tags.

When we execute home action, we get following output.

struts2-data-tags

Download project from above link and look into the data tags usage, play around with different attributes of these tags to learn more about them.

Thats all for Struts 2 data tags example tutorial, please read next post for Struts2 Control tags and UI tags in future articles.

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Current ye@r *

Subscribe to JournalDev Newsletter
Get the FREE access to Monthly Newsletter and Free PDF eBooks
*No Spam Guaranteed. By entering your email address, you agree also subscribing to our newsletter.
Oops! - Something went wrong.
Close
Oracle Magazine for Developers Download Now
Exclusive Offer: Citrix™ Whitepaper on Denial of Service Attack Download Now