简体   繁体   中英

Accessing JSTL <c:forEach> varStatus in JSP Expression

I have a JSP that imports an interface. The interface has a 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>

In [ctr.index] , it is saying ctr is unresolved. How do I access it inside the expression?

The variable ctr created in the page scope. To access page scope variable in JSP expression you can use pageContext implicit object.

<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>

But it seems ugly if you are using it with JSTL forEach tag. Better to construct the JSP EL expression.

<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>

Even this expression not necessary if you are using var attribute of the forEach tag which defines the variable referencing the element of the array, also in the page scope. You can access it like

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

Also see this question for other alternatives:
How to reference constants in EL?

Why do you need the index if you are already iterating the questions? Why do you use JSTL for the loop and scriptlets for the output?

If I understand your scenario correctly, this should look something like the below:

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

<bean:define id="questions" type="ph.edu.iacademy.message.Questions" />

<table>
    <c:forEach var="question" items="questions.QUESTION_ARRAY" >
        <tr>
            <td>${question.text}</td>
        </tr>
    </c:forEach>
</table>

If you really do want access to the status then you can do it as:

${ctr.index}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM