How to convert int to char in JSP expression language?

自作多情 提交于 2019-12-10 14:48:01

问题


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


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/4621836/how-to-convert-int-to-char-in-jsp-expression-language

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