Introduction
Sometimes while using the Struts2 Java framework, one might wonder how to assign value to a variable in the specified scope. The answer is using the set tag.
So, let us learn about the set tag.
The Set Tag
The Set Tag in Struts 2 is used to give a variable a value in a scope that has been defined. The scope can be application, session, request, page, or action where the action is the default scope. Here value means any hard-coded String, a property value, or simply anything you can reference.
Syntax: <s:set var="variable_Name" value="variable_Value" />
Action
Action class with - msg property
SetTagAct.java
package com.indra.common.action;
import com.opensymphony.xwork2.ActionSupport;
public class SetTagAct extends ActionSupport{
private String msg = "Struts 2 is a framework";
public String getMsg() {
return msg;
}
public String execute() throws Exception {
return SUCCESS;
}
}
Example
In the following example, you will learn how to use the set tag.
set.jsp
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<body>
<h1>Struts2 Set Tag Example</h1>
<h2>1. <s:set var="variable_Msg" value="msg" /></h2>
<s:set var="variable_Msg" value="msg" />
<s:property value="variable_Msg" />
<h2>2. <s:set var="variable_URL" value="%{'https://www.codingninjas.com/'}" /></h2>
<s:set var="variable_URL" value="%{'https://www.codingninjas.com/'}" />
<s:property value="variable_URL" />
</body>
</html>
Explanation -
-
<s:set var="variable_Msg" value="msg" />
It calls the getMsg() method of action and assigns the returned value to a variable named "variable_Msg". -
<s:set var="variable_URL" value="%{'https://www.codingninjas.com/'}" />
Hard-coded a string and assigned it to a variable named "variable_URL".
struts.xml
<?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="setTagAct"
class="com.indra.common.action.SetTagAct" >
<result name="success">pages/set.jsp</result>
</action>
</package>
</struts>
Output -