String to Long comparison throws “ELException: Cannot convert” in Tomcat 7, works in Tomcat 6

元气小坏坏 提交于 2019-12-05 09:09:41

This is because you are trying to compare a string to an int. Per the EL docs, section 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)

The problem with your test is that you are trying to compare "$12,345" (String) with 0 (Integer). Since 0 is an Integer, it falls into the bold If in their docs (above), where A or B is an Integer. Both are trying to be forced into a Long, which Java won't convert the String value "$12,345" into a long. If you change your code to either of the following you will see that it works:

String comparison:

<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>

Integer comparison:

<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>
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!