java - JSP 比较运算符行为

标签 java spring jsp el

我想比较 <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.E​​LException: Cannot convert No of type class java.lang.String to class java.lang.Long

关于比较:

JSP specification JSP.2.3.5.7 EL 版本 2.1,指定以下...

  1. If A is null or B is null return false for == or eq, true for != or ne

  2. 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.E​​LException 将抛出消息“Cannot将类型类 java.lang.String 的 No 转换为类 java.lang.Long"。

关于java - JSP 比较运算符行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24697840/

相关文章:

java - 无法在android中使用retrofit2发出@Post请求

Java:更新时读取文件

java - 没有为SQL参数'orgName'提供值:此SqlParameterSource为空

css - maven 会创建 css 文件的副本吗?

java - 无需 getter 即可访问 Model 类的私有(private)变量

java - 我是否犯了一个错误,或者 HijrahDate 库有问题?

java - Spring-batch @BeforeStep 不适用于 @StepScope

Spring - 如何销毁原型(prototype)范围的 bean?

java - scriptlet 标签 <%= some code %> 和 <# some code %> 之间的确切区别是什么?

java - 未调用 jsp 欢迎文件