tags:

views:

1464

answers:

3

Is it possible to access JSTL's forEach variable via code from within the loop?

<c:forEach items="${elements}" var="element">
    <% element.someMethod(); %>
</c:forEach>
A: 

If you use bean style access, this is possible. I don't remember the details of the spec but I think it is recommended to avoid relying on the generated servlet code from the JSP.

Josh
A: 

Edit following the correction of the example:

Yes, it is possible to access the var inside the c:forEach

Here's an example:

<c:forEach items="${elements}" var="element">
    ${((Element)element).someMethod()}
</c:forEach>

See c:forEach in the JSTL Documentation.

Ken Gentle
+1  A: 

Well, I believe "element" is stored in the page context.

<c:forEach items="${elements}" var="element">
    <% ((Element) pageContext.getAttribute("elements")).someMethod(); %>
</c:forEach>
sblundy
Just out of idle curiosity, where'd you find this method of access?
Ken Gentle
I've put things in session and request contexts many times for use in a JSP. Plus I knew that the page context is like them.
sblundy