java JSTL 字符串比较总是返回 false
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4196396/
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
JSTL string comparison always returns false
提问by user509755
I am trying string comparison with
我正在尝试字符串比较
<c:if test="${dept eq 'account'}"></c:if>
But this always returns false
. I check the dept variable had the value 'account'
. I also tried like this
但这总是返回false
。我检查了 dept 变量的值'account'
。我也试过这样
<c:if test="${dept == 'account'}"></c:if>
This also returns false
.
这也返回false
.
But if I use the java code like this then it works fine
但是如果我使用这样的java代码那么它工作正常
<%
if(dept.equals("account")){
blah blah blah
}
%>
Any help would be really appreciated.
任何帮助将非常感激。
Thanks
谢谢
回答by BalusC
The symptoms indicate that you've declared it in the scriptletscope, not in the EL scope. Scriptletsand EL doesn't share the same scope. EL uses under the covers PageContext#findAttribute()
to resolve the variable. Put dept
in one of the page, request, session or application scopes. Which one to choose depends on the sole purpose of dept
itself. I'd start with the request scope. E.g. in a servlet:
这些症状表明您已经在scriptlet范围内而不是在 EL 范围内声明了它。Scriptlet和 EL 不共享相同的范围。EL 在幕后使用PageContext#findAttribute()
来解析变量。放入dept
页面、请求、会话或应用程序范围之一。选择哪一个取决于dept
它本身的唯一目的。我将从请求范围开始。例如在 servlet 中:
request.setAttribute("dept", dept);
This way it'll be available in EL by ${dept}
.
这样它就可以在 EL 中通过${dept}
.
After all, best is to avoid using scriptletscompletely. Java code belongs in Java classes, not in JSP files.
毕竟,最好完全避免使用scriptlet。Java 代码属于 Java 类,而不属于 JSP 文件。