JSP比较运算符的行为 [英] JSP comparison operator behaviour
问题描述
我想比较JSP的<c:if>
标记中的两种不同类型.基本上,左一个总是Number
,右一个是字符串,如果该字符串可以解析为数字,我不会收到任何错误,但是如果字符串不能解析为Number
,我会收到javax.el.ELException: Cannot convert No of type class java.lang.String to class java.lang.Long
.
I want to compare two different types in <c:if>
tag of JSP. Basically left one is Number
always but right one is a String and If that string could be parse to a Number I receive no error but If the String cant be parsed to a Number
I receive javax.el.ELException: Cannot convert No of type class java.lang.String to class java.lang.Long
.
实际上:
$ {1 =="}//正常运行
$ {1 =="4"}//正常运行
$ {1 ==是"} //触发异常.
${1 =="" } //works fine
${1 =="4" } //works fine
${1 =="Yes" } //triggers the Exception.
但是,即使第3次比较在以前的JSP版本中也能正常工作,但现在它会导致异常.
But even the 3rd comparison worked fine in previous versions of JSPs but now it causes exceptions.
==
的行为是否在一段时间内发生了变化?
Has the behaviour of ==
changed over period of time?
任何建议都将受到赞赏
推荐答案
==
的行为未更改,但{expr}
的行为已更改...
Behavior of ==
is not changed but behavior of {expr}
is changed...
关于版本:
在 JSP规范
如果指定的版本小于2.1,则{expr}语法为 只需作为String文字处理即可.
If the version specified is less than 2.1, then the {expr} syntax is simply processed as a String literal.
因此,直到EL 2.0都将被视为字符串文字并与.equals
进行比较,因为==
将在内部转换为equals
(
So, till EL 2.0 all will be treated as a string literal and compared with .equals
as ==
will be converted to equals
internally (Reference here), but in 2.1 It will not be converted to string and will throw exception saying that javax.el.ELException: Cannot convert No of type class java.lang.String to class java.lang.Long
关于比较:
在 EL版本2.1的JSP规范JSP.2.3.5.7 ,指定了以下内容...
In JSP specification JSP.2.3.5.7 of EL version 2.1, following is specified...
-
如果A为null或B为null,则对于==或eq返回false,对于!=或ne返回true
If A is null or B is null return false for == or eq, true for != or ne
如果A或B为字节,短,字符,整数或长强制A 和B到Long,应用运算符
If A or B is Byte, Short, Character, Integer, or Long coerce both A and B to Long, apply operator
所以,在第一种情况下
${1 =="" } // ans is false as second one is null as per 1st rule.
在第二种情况下,
${1 =="4" } // ans is false as both are different after coercing to Long as per 2nd rule.
在上述情况下,通过内部类型转换,两者都将被强制为long.
Both will be coerced to long in above case with internal type conversion.
但是在第三种情况下,
${1 =="Yes" }
其中第二个字符串是字符串,不能被转换(强制)为Long,并且将抛出java.el.ELException
并显示消息无法将类型java.lang.String类型的No转换为java.lang.Long类".
But not in the third case,
${1 =="Yes" }
where second one is string can not be converted (coerced) to Long and java.el.ELException
will be thrown with message "Cannot convert No of type class java.lang.String to class java.lang.Long".
这篇关于JSP比较运算符的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!