我想根据以下条件循环打印记录表:
如果记录数超过35,我将需要暂停循环,插入页脚和下一页的新标题,并继续计数直到最后一条记录。
这里的条件是只使用jsp经典的scriplet。
这就是我所拥有的东西,我被困住了:(伪代码格式)
<% int j=0;
for(int i=0; i < list.size(); i++){
col1 = list.get(i).getItem1();
col2 = list.get(i).getItem2();
col3 = list.get(i).getItem3();
j++;
if (j==35) {%> // stops to render footer and next page's header
</table>
<table>
<!-- footer contents -->
</table>
<table>
<!-- header for next page -->
</table>
<%}%>
<tr><td><%=col1%></td><td><%=col1%></td><td><%=col1%></td></tr>
<%}%>
这个模型的问题是,如果我在这里使用了一个中断,我会停止循环,我不能从记录#36循环到记录结束。 我该怎么做呢?
答案 0 :(得分:0)
使用if (i % 35 == 0)
编写页脚,然后验证列表中是否有更多元素,因此您必须添加新表及其标题。代码如下所示:
<!-- table header -->
<%
int size = list.size();
int i = 0;
for(Iterator<YourObject> it = list.iterator(); it.hasNext(); ) {
i++;
YourObject someObject = it.next();
col1 = someObject.getItem1();
col2 = someObject.getItem2();
col3 = someObject.getItem3();
if (i % 35 == 0) {
%>
<!-- table footer -->
<%
if (i < size) {
%>
<!-- breakline and new table header -->
<%
}
}
}
%>
<!-- table footer -->
请注意,在此代码示例中,我使用Iterator
而不是List#get(int index)
,因为如果您的List
在内部是LinkedList
,则需要遍历所有元素,直到到达所需索引上的元素(在本例中为i
)。通过这种实现,您的代码更加清晰。
答案 1 :(得分:0)
如果您不想使用正确的分页,请使用JSTL,如下所示。除了显而易见的好处之外,阅读也比阅读更容易。
//The counter variable initialization
<c:set var="counter" value="0" scope="page"/>
<c:forEach items="${itemList}" var="item">
//Counter increment
<c:set var="counter" value="${counter + 1}" scope="page"/>
<tr>
<td>${item.propertyOne}</td>
<td>${item.propertyOne}</td>
</tr>
<c:if test="${counter % 35 == 0}">
//Include your footer here.
</c:if>
</c:forEach>