tadaaaam when somestrin...">

Char comparison in EL expression

I want to do something like this:

<c:if test="${somestring.charAt(0)=='1'}"> tadaaaam </c:if> 

when somestring is "11011", but this does not work. I can print it with

 ${somestring.charAt(0)} 

and this is "1", but the comparison above is not performed. The following comparison:

 if(somestring.charAt(0)=='1') 

worx (condition true) in pure Java.

Any ideas?

+6
source share
2 answers

EL has problems with char. Here is the only way to make it work.

 <c:if test="${somestring.charAt(0) == '1'.charAt(0)}" > tadaaaam </c:if> 
+8
source

The behavior is exactly as expected and as required by the EL specification. If you accept version 2.2 of the EL specification, you need to look at section 1.8.2, which contains the rules for the "==" operator.

In this case, the operands are somestring.charAt(0) , which are char and '1' , which are String (NOT a char), since strings can be separated by single or double quotes in EL.

Given that we have Character == String, then the sixth bundle 1.8.2 is applied, and both are force bound to Long values. The character will be forced to the value 49 (ASCII code for 1), and 1 to 1. They are not equal, therefore, the result you see.

I understand that this is not what you expect, but this is the behavior required by the specification and is caused by the fact that single quotes in EL limit strings, not characters.

+7
source

Source: https://habr.com/ru/post/915446/


All Articles