Passing c:forEach variable to a jsp:include

我怕爱的太早我们不能终老 提交于 2019-11-30 07:55:10

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/7799716/passing-cforeach-variable-to-a-jspinclude

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!