Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 550
Christian 'fuzi' Orgler Avatar asked Nov 13 '10 17:11

Christian 'fuzi' Orgler


2 Answers

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.

like image 163
skaffman Avatar answered Oct 14 '22 22:10

skaffman


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>
like image 39
Asaph Avatar answered Oct 14 '22 20:10

Asaph