Question

I want to check value of variable bool_val using Struts 2 tag <s:if> but it's not working.

<%@ taglib prefix="s" uri="/struts-tags" %>

<%boolean bool_val=true;%>
real value : <%=bool_val%></br>
expression evaluated value : 
<s:if test="%{bool_val==true}">
    TRUE
</s:if><s:else>
    FLASE
</s:else>

I also tried following test expressions too, but still not working.

<!-- 
bool_val
bool_val==true
%{bool_val}
%{bool_val==true}
%{bool_val=="true"}
 -->
Was it helpful?

Solution 3

You can't use a scriptlet variable in Struts tags unless you put this variable to the value stack. But you'd better not use a scriptlet variable, but the variable value.

<%@ taglib prefix="s" uri="/struts-tags" %>

<%boolean bool_val=true;%>
real value : <%=bool_val%><br/>
expression evaluated value : 
<s:set var="bool_val"><%=bool_val%></s:set>
<s:if test="#bool_val == 'true'">
    TRUE
</s:if><s:else>
    FALSE
</s:else>

OTHER TIPS

Use struts tag to create a variable like this

<s:set var="bool_val" value="true" />
expression evaluated value : 
<s:if test="%{#bool_val == true}">
    TRUE
</s:if><s:else>
    FALSE
</s:else>

Here is a sample tutorial.

There is a shorter version to the one suggested by Visruth CV :

<s:set var="foo" value="true" />

expression evaluated value : 
<s:if test="foo">
    TRUE
</s:if><s:else>
    FALSE
</s:else>

In case you want to check the boolean value against an Action attribute, here is the way to go :

class FooAction extends ActionSupport {
    private Boolean _bar = true;

    public Boolean isBar() { return _bar; }
}

And in the jsp file :

expression evaluated value : 
<s:if test="isBar()">
    TRUE
</s:if>
<s:else>
    FALSE
</s:else>

If getter method for your boolean variable in Action class is isBool() then use <s:if test="bool">. The key is to remove is from the method name and use. For example, if method is isApple() use <s:if test="apple">.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top