Struts2 set tag example. How to access struts2 variable in jsp scriptlet?

The struts2 <s:set> tag is used to assign a value / expression to a variable.  Suppose you want to edit the value of one field based on the other field’s value in  JSP.   For e.g. mobileNo field should be editable based on the userid. If the userid is admin, then the mobileNo should be editable otherwise  it should be read only. One way to do this  is to  use a variable and a scripting variable. i.e.  You can assign a  property value to a variable using <s:set> tag and the variable can be converted to scripting variable using  <jsp:useBean> tag. The same task can be done in struts 1.2  using  <bean:define> tag. Now let us see the code for using <s:set> tag.

SetTagAction.java

package net.javaonline.action;

import com.opensymphony.xwork2.ActionSupport;

public class SetTagAction extends ActionSupport {

	String userRole="";
	String mobileNo="";

	public String getMobileNo() {
		return mobileNo;
	}

	public void setMobileNo(String mobileNo) {
		this.mobileNo = mobileNo;
	}

	public String getUserRole() {
		return userRole;
	}

	public void setUserRole(String userRole) {
		this.userRole = userRole;
	}

	public String execute() throws Exception {

		setUserRole("admin");
		//setUserRole("user1");
		setMobileNo("9999999999");

		return SUCCESS;
	}

} 

SetTagExample.jap

<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title>Set Tag Example</title>
</head>
<body>
<s:actionerror/>
<s:form name="setTagForm" action="process.action" metod="post" >
<TABLE id="rtbl" width="350px" border="1">
  <TR>
  <td>
  <s:set var="role" value="userRole" />
  <jsp:useBean id="role" type="java.lang.String" />
  <%
	  if (role.equals("admin")) {%>
  		Mobile Number (Editable) :	<s:textfield name="mobileNo"/>
  <%} else{ %>
  		Mobile Number (Read Only) :	<s:property value="mobileNo"/>
  <%}%>

 </td>
</TR>
</TABLE>
</s:form>
</body>
</html>

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.enable.DynamicMethodInvocation" 	value="false" />
	<constant name="struts.devMode" value="false" />

	<package name="default" extends="struts-default" namespace="/">

	<action name="setTag" class="net.javaonline.action.SetTagAction">
  		<result name="success">SetTagExample.jsp</result>
       </action>	  

	</package>
</struts>

Run the program by calling :

http://localhost:8080/Structs2Dynamic/setTag.action

if userid is admin

set tag example output1

 

if userid is not admin

set tag example output2

 

Reference : Struts2 Set Tag

You may also like

Leave a Reply

Be the First to Comment!