在Jsp頁面中,我們也許有這樣的需求:從后端獲取到多個List,但又想將這些List的值同時打印出來
比如,
有用戶列表userList,user類有用戶ID、用戶名、用戶性別等基本信息
有用戶關系列表userRelationsList,userRelation類有用戶關注的用戶數、粉絲數等關系信息
在后端進行數據庫操作時,對用戶列表進行遍歷,將每次查詢得到的用戶的關系信息存入用戶關系列表中,每個用戶關系列表userRelationsList對應位置的用戶關系就與用戶對應,即userRelationList[i](第i個userRelation)的用戶關系就是第i個用戶的用戶關系
目前,我們想在頁面輸出用戶的信息,包括基本信息和關系信息
用戶名 | 用戶性別 | 用戶關注的用戶數 | 用戶粉絲數 |
HuskySir | 男 | 1 | 1 |
使用jstl的<forEach>標簽
<forEach>標簽
屬性 | 描述 | 是否必要 | 默認值 |
items | 要被循環的信息 | 否 | 無 |
begin | 開始的元素(0=第一個元素,1=第二個元素) | 否 | 0 |
end | 最后一個元素(0=第一個元素,1=第二個元素) | 否 | Last element |
step | 每一次迭代的步長 | 否 | 1 |
var | 代表當前條目的變量名稱 | 否 | 無 |
varStatus | 代表循環狀態的變量名稱 | 否 | 無 |
其中的varStatus為狀態項,有4個屬性值
屬性 | 描述 |
current | 當前迭代的項 |
index | 此項的索引,從0開始 |
count | 此項的計數序號,從1開始 |
first | 此項是否是第一項,布爾值 |
last | 此項是否是最后一項,布爾值 |
其中index為迭代的索引,count為從1開始的迭代計數,index=count-1
1 <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> 2 3 <table class="table table-hover table-bordered table-condensed"> 4 <tr style="text-align: center;font-size: 15px;"> 5 <td><strong>用戶名</strong></td> 6 <td><strong>用戶性別</strong></td> 7 <td><strong>用戶關注的用戶數</strong></td> 8 <td><strong>用戶粉絲數</strong></td> 9 </tr> 10 <c:forEach items="${userList}" var="user" varStatus="loop"> 11 <tr style="text-align: center;font-size: 10px;"> 12 <td><c:out value="${user.user_nickname}"></c:out></td> 13 <td><c:out value="${user.user_sex}"></c:out></td> 14 <td><c:out value="${userRelationList[loop.index].to_user_count}"></c:out></td> 15 <td><c:out value="${userRelationList[loop.index].from_user_count}"></c:out></td> 16 </tr> 17 </c:forEach> 18 </table>
我們可以通過varStatus中的index索引值,返回其他列表中的元素並打印