tags:

views:

34

answers:

3

So im trying to do something that might not be possible. I want to iterate through something like this:

i is set as an iterator

<c:forEach begin="1" end="${total}" var="i">
   <td>${prod${i}.name}</td>
</c:forEach>

This Obviously doesnt work, but I think it portrays what im trying to do.

I want to concatenate a variable to another variable where i is what i want to concatenate to prod.name. Normally product name would be something like this ${prod1.name}. So i want to replace 1 with an iterator as it goes through the loop.

Im very new to JSP and EL type developer. So if im doing this completely wrong please tell me.

Thanks

+1  A: 

Can't be done. My advice is to restructure your code so that prod is an array or a collection, then use c:forEach to iterate over its elements.

Mike Baranczak
Thanks, I was kinda figuring that's what I would need to do
littlevahn
+1  A: 

The easiest (and most common way) to handle this kind of thing is to have your group of products be in a collection: e.g. you have a List of Product objects that is passed to the JSP, and then you do

<c:forEach items="${products}" var="product">
   <td>${product.name}</td>
</c:forEach>
JacobM
Thanks, I was kinda figuring that's what I would need to do
littlevahn
A: 

If the object's scope is known beforehand, then you can go around this by composing the key using <c:set> and grabbing the object directly from the scoped map using the brace notation. Here's an example assuming that ${prod1} and so on is to be obtained from the request scope:

<c:forEach begin="1" end="${total}" var="i">
   <c:set var="prod" value="prod${i}" />
   <td>${requestScope[prod].name}</td>
</c:forEach>

If it's in the session scope, use ${sessionScope[prod].name} instead and for the application scope, use ${applicationScope[prod].name} instead.

Regardless, this isn't the recommended approach. You should put a List<Product> in the scope and iterate over it the way as demonstrated by JacobM.

See also:

BalusC