Struts 2 If, ElseIf and Else tags are used to perform basic condition checking.
These are the following scenario in real world application to check the condition.
1. Condition checking using Boolean variable.
2. Condition checking using String object.
3. Condition checking using collection object / bean object
4. Condition checking using integer data type
1 Condition checking using Boolean variable.
<s:if test="booleanValue">
returning TRUE.
</s:if>
<s:else>
returning FALSE.
</s:else>
2 Condition checking using String object.
<s:if test="%{stringValue==null}">
string is null
</s:if>
<s:else>
string is not null
</s:else>
3 Condition checking using collection object / bean object
<s:if test="%{arrayList.size()==0}">
object size is zero
</s:if>
<s:else>
object size is greater than zero
</s:else>
4 Condition checking using integer data type
<s:if test="%{integerValue==0}">
integer is zero
</s:if>
<s:elseif test="%{integerValue > 0}">
integer is greater than zero
</s:elseif>
<s:else>
integer is lesser than zero
</s:else>
Jsp Page , On embedding all the above scenario in a complete Jsp page
<%@taglib uri="/struts-tags" prefix="s"%>
<html>
<head>
<title>ControlTag - If Else Condition</title>
</head>
<body>
<h4>Control Tag</h4>
// For Boolean Value
<s:if test="booleanValue">
returning TRUE.
</s:if>
<s:else>
returning FALSE.
</s:else>
// For String Value
<s:if test="%{stringValue==null}">
string is null
</s:if>
<s:else>
string is not null
</s:else>
// For Integer Value
<s:if test="%{integerValue==0}">
integer is Zero
</s:if>
<s:elseif test="%{integerValue > 0}">
integer is greater than zero
</s:elseif>
<s:else>
integer is lesser than zero
</s:else>
// For Object Value
<s:if test="%{arrayList.size()==0}">
object size is zero
</s:if>
<s:else>
object size is greater than zero
</s:else>
</body>
</html>
Acion Class
package com.simplecode.action;
import java.util.ArrayList;
import java.util.List;
import com.opensymphony.xwork2.Action;
public class ControlTag implements Action
{
private List<String> arrayList = new ArrayList<String>();
private String stringValue;
private boolean booleanValue;
private int integerValue;
public String execute()
{
arrayList.add("Simple");
arrayList.add("Code");
arrayList.add("Stuffs");
integerValue = -2;
booleanValue = true;
stringValue = "someValues";
return SUCCESS;
}
public List<String> getArrayList()
{
return arrayList;
}
public void setArrayList(List<String> arrayList)
{
this.arrayList = arrayList;
}
public String getStringValue()
{
return stringValue;
}
public void setStringValue(String stringValue)
{
this.stringValue = stringValue;
}
public boolean isBooleanValue()
{
return booleanValue;
}
public void setBooleanValue(boolean booleanValue)
{
this.booleanValue = booleanValue;
}
public int getIntegerValue()
{
return integerValue;
}
public void setIntegerValue(int integerValue)
{
this.integerValue = integerValue;
}
}