Struts 2 if / elseif / else Tag
In this section, we are going to lean about the Struts 2 if/elseif/else tag. These are the contol tags. If you want to check any conditions in view page like: JSP, velocity etc. Then you will use these tags.
Struts 2 if/elseif/else tag works as similar to other if/elseif/else. When your given condition is true then it will exedute under the if tag otherwise it test the elseif condition. If that condition is true then it will execute. Both are not true then it will autometically goes into else tag. You see the following example:
index.jsp:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0
Transitional//EN">
<html>
<head>
<title>Hello World Application</title>
</head>
<body>
<table border="0" cellpadding="0" cellspacing="0"
width="400">
<tr>
<td>
<h2>Welcome to Developerhelpway.com</h2>
<h3>Struts 2 Generic Tags Example</h3>
<b>Control Tags Example</b>
<ol>
<li><a href="doIf.action">IF/elseif/else
Tag Example</a></li>
</ol>
</td>
</tr>
</table>
</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="true" />
<!-- Add your package and namespace here -->
<package name="developerhelpway" namespace="/"
extends="struts-default">
<!-- Add your actions here -->
<!-- Generic Tags -->
<action name="doIf" >
<result>/pages/genericTags/IfTag.jsp</result>
</action>
<!-- Actions end-->
</package>
</struts>
|
IfTag.jsp:
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<title>Struts 2 If Tag</title>
</head>
<body>
<s:set name="site" value="%{'developerhelpway.com'}"/>
<s:if test="%{#site=='developerhelpway.com'}">
<s:property value="%{#site}" />
</s:if>
<s:elseif test="%{#site=='developerhelpway'}">
<s:property value="%{#site}" />
</s:elseif>
<s:else>
This is not valid site.
</s:else>
</body>
</html>
|
Output: