-6ren">
gpt4 book ai didi

java - 访问 JSTL varStatus in JSP Expression

转载 作者:行者123 更新时间:2023-11-30 06:15:26 25 4
gpt4 key购买 nike

我有一个导入接口(interface)的 JSP。该接口(interface)有一个 String[] QUESTION_ARRAY

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ page import="com.mypackage.message.Questions"%>

<table>
<c:forEach var="question" items="<%=Questions.QUESTION_ARRAY%>" varStatus="ctr">
<tr>
<td><%=Questions.QUESTION_ARRAY[ctr.index]%></td>
</tr>
</c:forEach>
</table>

[ctr.index] 中,它说 ctr 未解析。我如何在表达式中访问它?

最佳答案

在页面范围内创建的变量 ctr。要访问 JSP 表达式中的页面范围变量,您可以使用 pageContext 隐式对象。

<table>
<% pageContext.setAttribute("questions", Questions.QUESTION_ARRAY); %>
<c:forEach var="question" items="${questions}" varStatus="ctr">
<tr>
<td>
<%=Questions.QUESTION_ARRAY[((LoopTagStatus)pageContext.getAttribute("ctr")).getIndex()]%>
</td>
</tr>
</c:forEach>
</table>

但是如果你将它与 JSTL forEach 标签一起使用,它看起来很难看。最好构建 JSP EL 表达式。

<table>
<% pageContext.setAttribute("questions", new Questions(){}.QUESTION_ARRAY); %>
<c:forEach var="question" items="${questions}" varStatus="ctr">
<tr>
<td>
${questions[ctr.index]}
</td>
</tr>
</c:forEach>
</table>

如果您正在使用 forEach 标记的 var 属性,即使该表达式也不是必需的,它定义了引用数组元素的变量,也在页面范围内。您可以像访问它一样

<table>
<% pageContext.setAttribute("questions", Questions.QUESTION_ARRAY); %>
<c:forEach var="question" items="${questions}" >
<tr>
<td>
${question}
</td>
</tr>
</c:forEach>
</table>

另请参阅此问题以了解其他替代方案:
How to reference constants in EL?

关于java - 访问 JSTL <c :forEach> varStatus in JSP Expression,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28849840/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com