Reputation:
Inside a JSP, I need to programmatically construct variable names to access, e.g.
List of variables
Using a <c:forEach>
with ${variable + i}
will not suffice, since i
is sum to the variable.
Any suggestions?
Upvotes: 0
Views: 473
Reputation: 1108577
Use the <jsp:useBean class="java.util.HashMap">
trick.
<jsp:useBean id="variables" class="java.util.HashMap" />
<c:forEach items="${items}" var="item" varStatus="loop">
<c:set target="${variables}" property="variable${loop.index}" value="some" />
...
</c:forEach>
This basically creates a HashMap
in the page scope and puts the given variables as map keys. The associated map value is free to your choice. You can even use EL in it.
In order to access it, just use ${variables['variable1']}
the usual way and so on.
Upvotes: 2