Search code examples
jsparraylistforeachjstljsp-tags

Splitting an Arraylist in a table using a Foreach Loop in JSP


Here's the catch, I have an arrayList within a foreach loop in a jsp page shown below. So, I wanted to have 3 columns having 3 rows each which has continuous values. How am I suppose to apply this scenario in the simplest way?

To clarify:

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>


Solution

  • You are almost there, but I'm not sure what you are doing with the input in your code example. To get the table to only display 3 columns you could use the varStatus tag loop operator. The documentation shoes what methods are associated with it.

    <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>
    

    Check out these examples to learn more about the c:foreach tag.