使用计数器变量</c:>在JSTL <c:foreach =“”>中显示List元素

时间:2014-11-27 07:57:50

标签: java list jsp foreach jstl

我有一个for循环的scriptlet,它显示来自List<Schedule>的电影时间表。

<%
    @SuppressWarnings("unchecked")
    List<Schedule> scheduleList = 
        (ArrayList<Schedule>) session.getAttribute("scheduleList");

    for (int ctr = 0; ctr < scheduleList.size(); ctr++) {
%>

<tr>
    <td class="center">
        <input type="radio" name="selection" value="<%=ctr%>" required title="Please select a schedule." />
    </td>
    <td><%=scheduleList.get(ctr).getMallId()%></td>
    <td class="center"><%=scheduleList.get(ctr).getScheduleCinema()%></td>
    <td>PHP <%=scheduleList.get(ctr).getSchedulePrice()%></td>
    <td><%=scheduleList.get(ctr).getScheduleDate()%></td>
    <td><%=scheduleList.get(ctr).getScheduleTime()%></td>
    <td class="center"><%=scheduleList.get(ctr).getScheduleSeats()%></td>
</tr>

<%
    }
%>

以下是Schedule bean对象供参考:

public class Schedule {

    private int scheduleId;
    private int movieId;
    private String mallId;
    private int scheduleCinema;
    private BigDecimal schedulePrice;
    private Date scheduleDate;
    private Time scheduleTime;
    private int scheduleSeats;

    // getters and setters
}

我已设法使用所需的迭代次数(related thread)将其转换为JSTL。

<c:forEach var="ctr" begin="0" end="${scheduleList.size()-1}">
<tr>
    <td class="center">
        <input type="radio" name="selection" value="${ctr}" required title="Please select a schedule." />
    </td>
    <td>${schedule.mallId}</td>
    <td>${schedule.scheduleCinema}</td>
    <td>${schedule.schedulePrice}</td>
    <td>${schedule.scheduleDate}</td>
    <td>${schedule.scheduleTime}</td>
    <td>${schedule.scheduleSeats}</td>
</tr>
</c:forEach>

输出:

enter image description here

Firefox Inspector:

<tr>

    <td class="center">
        <input type="radio" title="Please select a schedule." required="" value="0" name="selection"></input>
    </td>
    <td></td>
    <td></td>
    <td></td>
    <td></td>
    <td></td>
    <td></td>

</tr>
<tr>

    <td class="center">
        <input type="radio" title="Please select a schedule." required="" value="1" name="selection"></input>
    </td>
    <td></td>
    <td></td>
    <td></td>
    <td></td>
    <td></td>
    <td></td>

</tr>

不幸的是,日程安排细节没有显示 如何在JSTL中显示Schedule中每个List<Schedule>元素的数据?

(顺便说一句ctr很重要,下一步行动需要它的价值。)

2 个答案:

答案 0 :(得分:3)

而不是

<c:forEach var="ctr" begin="0" end="${scheduleList.size()-1}">

使用:

<c:forEach var="schedule" items="${scheduleList}" varStatus="ctr">
<tr>
<td class="center">
    <input type="radio" name="selection" value="${ctr.index}" required title="Please select a schedule." />
</td>

对于ctr,您可以在forEach中维护单独的计数器变量和增量。

答案 1 :(得分:1)

您可以在varStatus

中使用var以及c:forEach变量
varStatus="loop"

并将其用作${loop.index}

e.g。请参阅example