使用JSP中的Foreach循环在表中拆分Arraylist

时间:2015-04-11 22:16:03

标签: jsp arraylist foreach jstl jsp-tags

这是catch,我在一个jsp页面的foreach循环中有一个arrayList,如下所示。所以,我希望有3列,每行3行,具有连续值。我怎么想以最简单的方式应用这个场景?

澄清:

Column1      Column2      Column3
 Data1        Data4        Data7
 Data2        Data5        Data8
 Data3        Data6        Data9


<table>
<c:set var="numCols" value="3"/>
<c:forEach items="${dataList}" var="info" varStatus = "status"> 
   <c:if test="${status.index % numCols == 0}">
    <tr>
    </c:if>
        <td><input type ="submit" class="data btnColor" 
                   value="${info.dataName}" label ="${info.dataId}" />
        </td>
        <c:if test="${status.count % numCols == 0 or status.last}">
    </tr>
    </c:if>
</c:forEach>

1 个答案:

答案 0 :(得分:0)

你几乎就在那里,但我不确定你在代码示例中对输入做了什么。要使表格仅显示3列,您可以使用varStatus标记循环运算符。文档记录了与之相关的方法。

<c:set var="numCols" value="3"/>
<c:set var="numRows" value="3"/>
<c:set var="rowCount" value="0"/>
<table>
    <tr>
        // Loop through each element in the dataList and assign it to a variable named info
        <c:forEach items="${dataList}" var="info" varStatus="status"> 
            // If the current row count is less than the number of row allowed, proceed
            <c:if test="${rowCount lt numRows}">
                // Output the element (info) into a table cell
                <td><input type ="submit" class="data btnColor" value="${info.dataName}" label ="${info.dataId}" /></td>
                // Check to see if the cell that was just created is the 3 one in the row,
                // excluding the very first cell of the table (because 0 % 0 is undefined)
                <c:if test="${status.count ne 0 && status.count % numCols == 0}">
                    // Increment the row count
                    <c:set var="rowCount" value="${rowCount + 1}"/>
                    // End that row and start a new one
                    </tr><tr>
                </c:if>
            </c:if>
        </c:forEach>
    </tr>
</table>

查看these examples以了解有关c:foreach标记的更多信息。