1

I have simple reqirement that I want to compare Java Char to Integer in EL syntax, How do I do it ?

<select name="rating" id="id-rating">
    <c:forEach var="i" begin="1" end="5" > 
        <c:choose>
            <c:when test="${javaObject.rating == i }">
                <option value="${i }" selected="selected">${i }</option>
            </c:when>
            <c:otherwise>
                <option value="${i }">${i }</option>
            </c:otherwise>
        </c:choose>
    </c:forEach>
</select>${javaObject.rating }

I tried

  1. "eq" for comaprison
  2. varStatus variable eg loop.index
  3. also loop.current

${javaObject.rating } is what i'm getting from Java Class ( Spring Controller )

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Shantaram Tupe
  • 1,646
  • 3
  • 16
  • 42

2 Answers2

2

This works fine for me

${1 eq Integer.parseInt('1')} // return true
Braj
  • 46,415
  • 5
  • 60
  • 76
1

This indeed won't work. The technical problem is, the char 1 has an integer value of 49. (the code point). Evidence is here:

System.out.println((int) '1'); // 49

So, you need to add an integer offset to match the char's code point.

<c:forEach var="i" begin="49" end="53"> 
    ${bean.rating == i}<br/>
</c:forEach>

Alternatively, use <c:set> with the value in body to convert the value to String. EL will then do automatic coercion the right way.

<c:forEach var="i" begin="1" end="5">
    <c:set var="ratingAsString">#{bean.rating}</c:set>
    ${ratingAsString == i}<br/>
</c:forEach>

See also:

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • thanks a lot again , you solved my another issue, in which I'm comparing char from bean to 'Y' or 'N'. previously I converted both to String to get result.. Your 2nd link is very helpful ... – Shantaram Tupe Feb 11 '16 at 09:56
  • Once again, you help me for this, concatenation of String with number, http://stackoverflow.com/a/6297285/3425489 thanks a lot , since I do not have 50 reputation , can't comment over there.... – Shantaram Tupe Aug 09 '16 at 13:05