JSTL forEach 在 javacode 中使用变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4173797/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 12:19:50  来源:igfitidea点击:

JSTL forEach use variable in javacode

javajspforeachjstl

提问by Christian 'fuzi' Orgler

I want to use the actual item from my c:forEachin a <% JavaCode/JSPCode %>. How do I access to this item?

我想使用我的c:forEachin 中的实际项目<% JavaCode/JSPCode %>。我如何访问这个项目?

<c:forEach var="item" items="${list}">
   <% MyProduct p = (MyProduct) ${item}; %>   <--- ???
</c:forEach>

采纳答案by Asaph

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:

不要使用 scriptlet(即<% %>标签之间的内容。这被认为是不好的做法,因为它鼓励在视图上下文中放置太多代码,甚至是业务逻辑。相反,只使用 JSTL 和 EL 表达式。试试这个:

<c:forEach var="item" items="${list}">
    <c:set var="p" value="${item}" />
</c:forEach>

回答by skaffman

Anything that goes inside <% %>has to be valid Java, and ${item}isn't. The ${...}is JSP EL syntax.

任何进入内部的东西<% %>都必须是有效的 Java,但${item}不是。这${...}是 JSP EL 语法。

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.

然而,这是编写 JSP 的一种可怕的方式。当您已经在使用 JSTL/EL 时,为什么要使用 scriptlet?很明显,你在里面放了一些东西<forEach>,不管它是什么,你应该能够在不使用 scriptlet 的情况下做到这一点。