在Jsp頁面中,咱們也許有這樣的需求:從後端獲取到多個List,但又想將這些List的值同時打印出來java
好比,數據庫
有用戶列表userList,user類有用戶ID、用戶名、用戶性別等基本信息後端
有用戶關係列表userRelationsList,userRelation類有用戶關注的用戶數、粉絲數等關係信息jsp
在後端進行數據庫操做時,對用戶列表進行遍歷,將每次查詢獲得的用戶的關係信息存入用戶關係列表中,每一個用戶關係列表userRelationsList對應位置的用戶關係就與用戶對應,即userRelationList[i](第i個userRelation)的用戶關係就是第i個用戶的用戶關係oop
目前,咱們想在頁面輸出用戶的信息,包括基本信息和關係信息spa
code
用戶名 | 用戶性別 | 用戶關注的用戶數 | 用戶粉絲數 |
HuskySir | 男 | 1 | 1 |
使用jstl的<forEach>標籤blog
<forEach>標籤索引
屬性 | 描述 | 是否必要 | 默認值 |
items | 要被循環的信息 | 否 | 無 |
begin | 開始的元素(0=第一個元素,1=第二個元素) | 否 | 0 |
end | 最後一個元素(0=第一個元素,1=第二個元素) | 否 | Last element |
step | 每一次迭代的步長 | 否 | 1 |
var | 表明當前條目的變量名稱 | 否 | 無 |
varStatus | 表明循環狀態的變量名稱 | 否 | 無 |
其中的varStatus爲狀態項,有4個屬性值element
屬性 | 描述 |
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索引值,返回其餘列表中的元素並打印