Struts 2 set tag example
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 :
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. <s:set var="varMsg" value="msg" /></h4> <s:set var="varMsg" value="msg" /> <s:property value="varMsg" /> <h4>2. <s:set var="varUrl" value="%{'http://www.mkyong.com'}" /></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“.
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







How set something like
<s:set name="ipAdd" value="%{}”