Struts 2 “set” tag is used to assign a value to a variable in a specified scope (application, session, request, page, or action), the action is the default scope. See a complete “set” tag example :

The “value” means any hard-coded String, property value or just anything you can reference.

1. Action

Action class with a “msg” property.

SetTagAction.java

package com.mkyong.common.action;
 
import com.opensymphony.xwork2.ActionSupport;
 
public class SetTagAction extends ActionSupport{
 
	private String msg = "Struts 2 is a funny framework";
 
	public String getMsg() {
		return msg;
	}
 
	public String execute() throws Exception {
 
		return SUCCESS;
	}
}

2. set tag example

It shows the use of “set” tag.

set.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
</head>
 
<body>
<h1>Struts 2 set tag example</h1>
<h4>1. &lt;s:set var="varMsg" value="msg" /&gt;</h4>
 
<s:set var="varMsg" value="msg" />
<s:property value="varMsg" />
 
<h4>2. &lt;s:set var="varUrl" value="%{'http://www.mkyong.com'}" /&gt;</h4> 
 
<s:set var="varUrl" value="%{'http://www.mkyong.com'}" />
<s:property value="varUrl" />
 
 
</body>
</html>

How it work?

1. <s:set var=”varMsg” value=”msg” />
Call the action’s getMsg() method and assign the returned value to a variable named “varMsg“.

2. <s:set var=”varUrl” value=”%{‘http://www.mkyong.com’}” />
Hard coded a string and assign it to a variable named “varUrl“.

Assign value to a variable, not property value.

For example,

public class SetTagAction extends ActionSupport{
 
	private String msg;
 
	public String setMsg(String msg) {
		this.msg = msg;
	}
	...
<s:set var="msg" value="%{'this is a message'}" />

Many Struts 2 developers thought that the “set” tag var=”msg” will assign the value to the associated action class via setMsg() method.

This is wrong, the set tag will not call the setMsg() method, it will only assign the “value” to a variable named “msg“, not the action’s property value.

3. 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="setTagAction" 
			class="com.mkyong.common.action.SetTagAction" >
			<result name="success">pages/set.jsp</result>
		</action>
 
	</package>
</struts>

5. Demo

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

Output

Struts 2 set tag example

Reference

  1. Struts 2 set tag documentation
Note : You can find more similar articles at - Struts 2.x Tutorials