How to nest an EL expression in another EL expression
I'm writing JSP / JSTL, and I'm trying to iterate over several items in a database.
I currently have three columns in the database, ${image1}
, ${image2}
and ${image3}
. I'm trying to use the following code to print out information for them:
<c:forEach begin="1" end="3" var="i">
${image${i}}
</c:forEach>
Is there any way I can make this work?
Solution 1:
You can't nest EL expressions like that.
You can achieve the concrete functional requirement only if you know the scope of those variables beforehand. This way you can use the brace notation while accessing the scope map directly. You can use <c:set>
to create a new string variable in EL scope composed of multiple variables. You can use e.g. ${requestScope}
to access the mapping of request scoped variables.
Thus, provided that you've indeed stored those variables in the request scope, then this should do:
<c:forEach begin="1" end="3" var="i">
<c:set var="image" value="image${i}" />
${requestScope[image]}
</c:forEach>
For the session scope, use the ${sessionScope}
map instead.
See also:
- Our EL wiki page
- String Concatenation in EL