以下代码段在 Tomcat 6 中运行良好,
<c:set var="abc" value="$12,345" />
<c:choose>
<c:when test="${abc ne 0}">
<c:out value="PASS"></c:out>
</c:when>
<c:otherwise>
<c:out value="FAIL"></c:out>
</c:otherwise>
</c:choose>
但在 Tomcat 7 中抛出异常。
javax.el.ELException: Cannot convert $1,2345 of type class java.lang.String to class java.lang.Long
at org.apache.el.lang.ELSupport.coerceToNumber(ELSupport.java:304)
at org.apache.el.lang.ELSupport.coerceToNumber(ELSupport.java:283)
at org.apache.el.lang.ELSupport.equals(ELSupport.java:143)
at org.apache.el.parser.AstNotEqual.getValue(AstNotEqual.java:40)
at org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:185)
at org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate(PageContextImpl.java:1026)
at org.apache.jsp.WEB_002dINF.jsp.web.statussummary.status_005fsummary_jsp._jspx_meth_c_005fwhen_005f0(status_005fsummary_jsp.java:290)
看来
${abc ne 0}
的表达方式有区别在 Tomcat 7 中被评估。在 Tomcat 6 中 ${abc}
和 ${0}
被比较为字符串,但在 Tomcat 7 中我得到了这个异常。我不知道为什么会发生这种情况以及哪个 API 的哪个类文件对此负责。这是怎么引起的,我该如何解决?
最佳答案
这是因为您正在尝试将字符串与 int 进行比较。每 EL docs ,第 1.8.2 节:
A {==,!=,eq,ne} B
■ If A==B, apply operator
■ If A is null or B is null return false for == or eq, true for != or ne.
■ If A or B is BigDecimal, coerce both A and B to BigDecimal and then:
■ If operator is == or eq, return A.equals(B)
■ If operator is != or ne, return !A.equals(B)
■ If A or B is Float or Double coerce both A and B to Double, apply operator
■ If A or B is BigInteger, coerce both A and B to BigInteger and then:
■ If operator is == or eq, return A.equals(B)
■ If operator is != or ne, return !A.equals(B)
■ If A or B is Byte, Short, Character, Integer, or Long coerce both A and B to Long, apply operator
■ If A or B is Boolean coerce both A and B to Boolean, apply operato
■ If A or B is an enum, coerce both A and B to enum, apply operatorr
■ If A or B is String coerce both A and B to String, compare lexically
■ Otherwise if an error occurs while calling A.equals(B), error
■ Otherwise, apply operator to result of A.equals(B)
您的测试的问题在于您试图比较
"$12,345"
(字符串)与 0
(整数)。自 0
是一个整数,它落入粗体 如 在他们的文档(上)中,其中 A 或 B 是一个整数。两者都试图被强制为 Long,Java 不会转换 String 值 "$12,345"
成长。如果您将代码更改为以下任一方式,您将看到它有效:字符串比较:
<c:set var="abc" value="$12,345" />
<c:choose>
<c:when test="${abc ne '0'}"> <!-- Change Integer to String -->
<c:out value="PASS"></c:out>
</c:when>
<c:otherwise>
<c:out value="FAIL"></c:out>
</c:otherwise>
</c:choose>
整数比较:
<c:set var="abc" value="12345" /> <!-- Change String to Integer -->
<c:choose>
<c:when test="${abc ne 0}">
<c:out value="PASS"></c:out>
</c:when>
<c:otherwise>
<c:out value="FAIL"></c:out>
</c:otherwise>
</c:choose>
关于jsp - String to Long 比较在 Tomcat 7 中抛出 "ELException: Cannot convert",适用于 Tomcat 6,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25274458/