我想比较 <c:if>
中的两种不同类型JSP 的标记。基本上剩下一个是Number
总是但正确的一个是字符串,如果该字符串可以解析为数字,我不会收到任何错误,但如果无法将字符串解析为 Number
我收到 javax.el.ELException: Cannot convert No of type class java.lang.String to class java.lang.Long
.
实际上:
${1 =="" } //works fine
${1 =="4" } //works fine
${1 =="Yes" } //triggers the Exception.
但即使是第 3 次比较在以前版本的 JSP 中也能正常工作,但现在它会导致异常。
具有 ==
的行为随着时间的推移发生了变化?
非常感谢任何建议
最佳答案
==
的行为没有改变,但是 {expr}
的行为改变了...
关于版本:
在 JSP Specification, 的向后兼容性部分
If the version specified is less than 2.1, then the {expr} syntax is simply processed as a String literal.
因此,直到 EL 2.0 all 都将被视为字符串文字并与 .equals
进行比较,因为 ==
将被转换为 equals
在内部 ( Reference here ),但在 2.1 中它不会被转换为字符串,并且会抛出异常说明 javax.el.ELException: Cannot convert No of type class java.lang.String to class java.lang.Long
关于比较:
在JSP specification JSP.2.3.5.7 EL 版本 2.1,指定以下...
If A is null or B is null return false for == or eq, true for != or ne
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。
但不是第三种情况,
${1 =="Yes"}
其中第二个是字符串无法转换(强制)为 Long 并且 java.el.ELException
将抛出消息“Cannot将类型类 java.lang.String 的 No 转换为类 java.lang.Long"。
关于java - JSP 比较运算符行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24697840/