How to convert int to char in JSP expression language?
Asked Answered
P

2

5

I need to display incremented single characters to denote footnotes in a table of data in a JSP. In Java I would normally have a char variable and just increment it, or convert an int to a char by casting it (e.g. (char)(i + 97) to convert a 0-based index to a-z). I can't figure out how to do this in expression language short of writing my own JSTL function.

Does anyone know how to convert an int to char in EL? Or how to increment a char variable in EL? Or possibly even a better technique to do what I'm trying to do in JSP/EL?

Example of what I need to be able to produce:
a mydata
b myotherdata
...
a first footnote
b second footnote

Papp answered 7/1, 2011 at 1:48 Comment(0)
A
6

That's not possible. Your best bet is to display it as XML entity.

<c:forEach items="${list}" var="item" varStatus="loop">
    <sup>&#${loop.index + 97};</sup> ${item}<br />
</c:forEach>

It'll end up like as

<sup>&#97;</sup> item1<br />
<sup>&#98;</sup> item2<br />
<sup>&#99;</sup> item3<br />
...

The &#x61; represents an a and so on.

a item1
b item2
c item3
...

You've only a problem when the list is over 26 items.

Ama answered 7/1, 2011 at 3:27 Comment(1)
Thanks this is a good solution however &#x61; is the hex representation of an 'a' and so this didn't quite work (skipped the 10th to 16th letters when it got to &#x70;). The solution was to use &#97; etc which is the decimal equivalent.Papp
E
1

You can use c:set and xml entity tags to cast the integer to a character. You'll have to use the backslash in order to escape the # or, the id variable will be set to literally &#{(i.index+97)} rather than evaluating the ${...} code

The following example will loop through the "list" variables and output a div for each one with the id and contents starting at "a".

<c:forEach items="${list}" varStatus="i">
    <c:set var="id" value="&\#${(i.index+97)}" />
    <div id="div-${id}">Div ${id}</div>
</c:forEach>

This would output the following, assuming there are 5 elements in the "list" collection.

<div id="div-a">Div a</div>
<div id="div-b">Div b</div>
<div id="div-c">Div c</div>
<div id="div-d">Div d</div>
<div id="div-e">Div e</div>

As noted in the other answer, this will only work if your list size is under 27.

Extinctive answered 26/8, 2014 at 16:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.