14

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>

2 Answers 2

19

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.

Sign up to request clarification or add additional context in comments.

Comments

9

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.