Comparing numbers in EL expression does not seem to work

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-17 20:25:18

问题


In JSP, I want to compare two variables

If I do:

<c:set var="pagerTotDisp" value="9"/>
<c:if test="${pagerTotDisp > 8}">
  <span>pagerTotDisp above 8</span>
</c:if>

It displays "pagerTotDisp above 8" as expected

<c:set var="TotalPages" value="10"/>
<c:if test="${TotalPages > 2}">
  <span>TotalPages above 2</span>
</c:if>

It displays "pagerTotDisp above 8" as expected

But then if I do

<c:set var="pagerTotDisp" value="9"/>
<c:set var="TotalPages" value="10"/>
<c:if test="${TotalPages < pagerTotDisp}">
  <span>This condition is not true. This text should not be displayed</span>
</c:if>

It displays "This condition is not true. This text should not be displayed".

What's going on? Is that JSP not being able to handle two variables in a same condition??

thanks


回答1:


You're hardcoding the value in the value attribute of <c:set>. The <c:set> treats the hardcoded values as String. EL is therefore also evaluating them as String. Lexicographically, 9 is greater than 10, because 9 is at a further numerical position than 1.

There are two ways to solve this:

  1. Set the value via an EL expression. It will be interpreted as Long instead of String.

    <c:set var="pagerTotDisp" value="${9}" />
    <c:set var="TotalPages" value="${10}" /> 
    
  2. Or, use <fmt:parseNumber>, which would be the only solution if you have those as String variables from elsewhere which you have no control over.

    <fmt:parseNumber var="pagerTotDisp" value="9" />
    <fmt:parseNumber var="TotalPages" value="10" />
    



回答2:


It treats both values as Strings, and compares them lexicographically.

Try

<c:set var="pagerTotDisp" value="${9}"/>
<c:set var="TotalPages" value="${10}"/>
<c:if test="${TotalPages < pagerTotDisp}">
  <span>This condition is not true. This text should not be displayed</span>
</c:if>


来源:https://stackoverflow.com/questions/7164536/comparing-numbers-in-el-expression-does-not-seem-to-work

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