Need help using <c:forEach> in JSP/JSTL

谁说胖子不能爱 提交于 2019-12-05 19:45:43

You can't do that with plain HTML. You've mentioned HTML in the original question title, but since you've attached the javabeans tag and mentioned the c:forEach tag, I suppose you mean JSP and JSTL instead of HTML.
Here the JSP+JSTL solution, formatted to be better readable. The bean code:

package com;

public class TransferBean {
    private int[][] _boardArray = {
        { 1, 2, 33, 0, 7},
        { 13, 11, 7, 5, 3},
        { 5, 3, 2, 1, 1},
    };


    public int[][] getBoardArray() {
        return _boardArray;
    }

    public int getBoardArrayRowLength() {
        if (_boardArray == null || _boardArray.length == 0
                || _boardArray[0] == null) {
            return 0;
        }

        return _boardArray[0].length;
    }
}

Here the JSP file content:

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

<jsp:useBean id="bean" class="com.TransferBean" />

<table>
    <thead>
        <tr>
        <c:forEach var="i" begin="1" end="${bean.boardArrayRowLength}">
            <th>Column ${i}</th>
        </c:forEach>
        </tr>
    </thead>
    <tbody>
        <c:forEach var="row" items="${bean.boardArray}">
        <tr>
            <c:forEach var="column" items="${row}">
                <td>
                    ${column}
                </td>
            </c:forEach>
        </tr>
        </c:forEach>
    </tbody>
</table>

The array content is rendered by two nested c:forEach loops. The outer loop iterates over the rows, and for each row, the nested loop iterates over the columns in the given row.

Above example looks like this in a browser:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!