JSTL forEach use variable in javacode

I want to use the actual item from my c:forEach in a <% JavaCode/JSPCode %>. How do I access to this item?

<c:forEach var="item" items="${list}">
   <% MyProduct p = (MyProduct) ${item}; %>   <--- ???
</c:forEach>

Upvotes: 14

Views: 22385

Answers (2)

Asaph
Asaph

Reputation: 162851

Don't use scriptlets (ie. the stuff in between the <% %> tags. It's considered bad practice because it encourages putting too much code, even business logic, in a view context. Instead, stick to JSTL and EL expressions exclusively. Try this:

<c:forEach var="item" items="${list}">
    <c:set var="p" value="${item}" />
</c:forEach>

Upvotes: 9

skaffman
skaffman

Reputation: 403591

Anything that goes inside <% %> has to be valid Java, and ${item} isn't. The ${...} is JSP EL syntax.

You can do it like this:

<c:forEach var="item" items="${list}">
   <% MyProduct p = (MyProduct) pageContext.getAttribute("item"); %>   
</c:forEach>

However, this is a horrible way to write JSPs. Why do you want to use scriptlets, when you're already using JSTL/EL? Obviously you're putting something inside that <forEach>, and whatever it is, you should be able to do without using a scriptlet.

Upvotes: 19

Related Questions