Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am trying to iterate through a 2d array of integers and represent them in a grid using the <table> tag. The catch is that I am not allowed to use any java-script. I know it is something to the effect of the below code, but more complicated. And boardArray returns a 2d integer array. So how would I extract the value at each cell? There is a predetermined size of the array as well.

       <c:forEach var="array" items="${bean.boardArray}">
            <tr> 
                <td>${print out contents of a row}</td>
            </tr> 
        </c:forEach>
like image 474
user1205853 Avatar asked Dec 28 '22 05:12

user1205853


1 Answers

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:
JSTL iteration over 2D array

like image 170
t0r0X Avatar answered Jan 10 '23 01:01

t0r0X