char comparison in EL expression [duplicate]

老子叫甜甜 提交于 2019-12-12 10:39:57

问题


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?


回答1:


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>



回答2:


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.



来源:https://stackoverflow.com/questions/10542875/char-comparison-in-el-expression

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