char comparison in EL expression [duplicate]

2019-06-20 08:49发布

This question already has an answer here:

I want to do something like this:

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

when somestring is "11011" but it doesn't work. I can print it with

${somestring.charAt(0)}

and it is '1' but comparison above fails. The following comparison:

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

worx (condition is true) in pure Java.

Any ideas?

2条回答
何必那么认真
2楼-- · 2019-06-20 09:26

EL seems to have trouble with char. Here is the only way I could make it work.

<c:if test="${somestring.charAt(0)  == '1'.charAt(0)}" >
     tadaaaam
</c:if>
查看更多
欢心
3楼-- · 2019-06-20 09:35

The behaviour is exactly as expected and as required by the EL specification. If you take version 2.2 of the EL specification, you need to look at section 1.8.2 which provides the rules for the '==' operator.

The operands in this case are somestring.charAt(0) which is a char and '1' which is a String (NOT a char) since Strings may be delimited by either single or double quotes in EL.

Given we have Character == String, then the sixth bullet of 1.8.2 applies and both are coerced to Long values. The character will be coerced to 49 (the ASCII code for 1) and 1 is coerced to 1. These aren't equal hence the result you see.

I appreciate that this isn't what you would expect but it is the behaviour that is required by the specification and is triggered by the fact that single quotes in EL delimit Strings not chars.

查看更多
登录 后发表回答