Pregunta

I am trying to access some JSTL variables that were set on a JSTL for-loop in an include.

Example:

<c:forEach items="${cart.entries}" var="entry">
 <jsp:include page="helper.jsp"></jsp:include>
</c:forEach>

Inside helper.jsp I want to be able to reference the variable 'entry'. It keeps coming up as 'empty'. I thought maybe there might be a way to add scope to the forEach Variable like you can with normal set variables.

Any ideas?

¿Fue útil?

Solución

ANSWER: I ended up just having to do this to get it to work.

<c:forEach items="${cart.entries}" var="entry">
<c:set var="entryFC" value="${entry}" scope="request"></c:set>
 <jsp:include page="helper.jsp"></jsp:include>
</c:forEach>

Then i referenced the entryFC in my include. Not very elegant at all but its working so i guess ill go with it.

Otros consejos

I know it is very late to answer for this question, but can be helpful to those who stuck in this situation and searching for answers.

My answer will work if you are not not tightly bound to use <jsp: include> tag to include jsp. Instead, you can use <%@include file="/WEB-INF/views/path-to-jsp.jsp" %> to import another jsp in the page and this page can use your <c:forEach> tag looping variable.

For example.

<c:forEach items="${users}" var="user">

    <%@include file="/WEB-INF/views/path-to-jsp.jsp" %> <!-- here ${user} can be use in importing jsp file. -->
</c:forEach>

It is working because <%@include file="" %> tag will inject the contents of the named file into the JSP containing the tag, as if it was copied and pasted. This is done before the content of the included file is parsed, instead parsing it while the containing JSP is parsed. This is more akin to a C #include directive, where during pre-processing the included file is “pasted” into place before the file is compiled. After the content is included, it is evaluated, all in the same context, and therefore with the same accesses and constraints the included code would have if the contents were simply typed in place.

Whereas, <jsp:include page=""/> tag behaves differently in that the result of rendering the specified page is injected into the containing JSP at the point of the tag. This is done by essentially submitting the requested page to the same container, as a separate rendering request, and taking the results, not the content of the file. This request is done in its own context, meaning it doesn’t use the same page information as the page that contains the tag. This can be handy, especially if the included content may have conflicting variables, for example.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top