问题
I want to loop a table of records for printing, based on the following condition:
If the number of records is more than 35, I will need to pause the loop, insert a footer, and a new header for the next page and continue its count till the last record.
The condition here is to use only jsp classic scriplet.
Here is what I have and I am stuck: (in pseudo code format)
<% 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>
<%}%>
the problem with this model is that if I use a break inside this if, I'd stop the loop and I can't loop from record #36 to end of record. How do I go about doing this?
回答1:
Use an if (i % 35 == 0)
to write the footer and then validate if there are more elements in the list so you would have to add a new table and its header. The code would look like this:
<!-- 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 -->
Note that in this code sample I'm using Iterator
instead of List#get(int index)
since if your List
is a LinkedList
internally it would need to traverse all the elements until reach the element on the desired index (in this case, i
). With this implementation, your code is even cleaner.
回答2:
If you don't want to use proper pagination then use JSTL as below. Easier to read than scrip-lets as well, apart from the obvious benefits.
//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>
来源:https://stackoverflow.com/questions/17101453/jsp-insert-footer-based-on-condition-in-for-loop