Java <s:if> 布尔值的测试表达式评估没有按预期工作

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23075594/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 20:29:22  来源:igfitidea点击:

<s:if> test expression evaluation for boolean value doesn't work as expected

javajspstruts2ognlboolean-expression

提问by Akash Jain

I want to check value of variable bool_valusing Struts2 tag <s:if>but it's not working.

我想bool_val使用 Struts2 标签检查变量的值,<s:if>但它不起作用。

<%@ 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"}
 -->

采纳答案by Roman C

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.

您不能在 Struts 标签中使用 scriptlet 变量,除非您将此变量放入值堆栈。但是最好不要使用scriptlet 变量,而是使用变量值。

<%@ 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>

回答by Visruth

Use struts tag to create a variable like this

使用 struts 标签创建这样的变量

<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.

这是一个示例教程

回答by Simon

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

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 :

如果您想根据 Action 属性检查布尔值,可以使用以下方法:

class FooAction extends ActionSupport {
    private Boolean _bar = true;

    public Boolean isBar() { return _bar; }
}

And in the jsp file :

在jsp文件中:

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

回答by Rohit Reddy Abbadi

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

如果 Action 类中布尔变量的 getter 方法是isBool()使用<s:if test="bool">. 关键是去掉is方法名和使用。例如,如果方法是isApple()use <s:if test="apple">