JSP comparison operator behaviour
Asked Answered
L

2

8

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.

Practically:

${1 =="" } //works fine
${1 =="4" } //works fine
${1 =="Yes" } //triggers the Exception.

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?

Any suggestions are highly appreciated

Lakeesha answered 11/7, 2014 at 12:33 Comment(2)
maybe internally uses a number converter if you uses eq sure that doesn't throw an excp.Rebirth
no. Even eq throws the same exception in new JSP versionsLakeesha
M
6

Behavior of == is not changed but behavior of {expr} is changed...

About versions :

In backward compatibility section of JSP Specification,

If the version specified is less than 2.1, then the {expr} syntax is simply processed as a String literal.

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

About Comparision :

In JSP specification JSP.2.3.5.7 of EL version 2.1, following is specified...

  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

so, In first case,

${1 =="" } // ans is false as second one is null as per 1st rule.

and In second case,

${1 =="4" } // ans is false as both are different after coercing to Long as per 2nd rule.

Both will be coerced to long in above case with internal type conversion.

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

Metralgia answered 11/7, 2014 at 13:1 Comment(2)
can I do something to make my ELs in JSPs backward compatible?Lakeesha
I don't think there is any provision like that, unless you degrade .Metralgia
S
1

As of JSP 2.1, the JSP uses the unified expression language (unified EL), which represents a union of the expression language offered by JSP 2.0 and the expression language created for JavaServer Faces technology.

It is very likely that the behaviour can be a bit different.

See section 1.18 of the JavaServer Pages 2.1 Expression Language Specification (available from here) for the complete type conversion rules.

Suksukarno answered 11/7, 2014 at 12:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.