在Jsp页面中,我们也许有这样的需求:从后端获取到多个List,但又想将这些List的值同时打印出来
比如,
有用户列表userList,user类有用户ID、用户名、用户性别等基本信息
有用户关系列表userRelationsList,userRelation类有用户关注的用户数、粉丝数等关系信息
在后端进行数据库操作时,对用户列表进行遍历,将每次查询得到的用户的关系信息存入用户关系列表中,每个用户关系列表userRelationsList对应位置的用户关系就与用户对应,即userRelationList[i](第i个userRelation)的用户关系就是第i个用户的用户关系
目前,我们想在页面输出用户的信息,包括基本信息和关系信息
比如userList表中用户名、用户性别信息,userRelation表中用户关注的用户数、用户粉丝数,则需要同时遍历2个List
使用jstl的<forEach>标签
<forEach>标签
其中的varStatus为状态项,有4个属性值
其中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索引值,返回其他列表中的元素并打印