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> . The trick is that I'm not allowed to use java-script. I know this is something similar to the code below, but more complicated. And boardArray returns a 2d integer array. So, how could I extract the value in each cell? There is also a given array size.

  <c:forEach var="array" items="${bean.boardArray}"> <tr> <td>${print out contents of a row}</td> </tr> </c:forEach> 
+4
source share
1 answer

You cannot do this with plain HTML. You mentioned HTML in the original title of the question, but since you are attaching the javabeans tag and mention the c:forEach tag, I suppose you mean JSP and JSTL instead of HTML.
Here's a JSP + JSTL solution formatted for better reading. 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 is the contents of the JSP file:

 <%@ 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 contents of the array are rendered with two nested c:forEach loops. The outer loop repeats row by row, and for each row, a nested iteration loop through the columns in that row.

The example above looks in the browser:
JSTL iteration over 2D array

+10
source

Source: https://habr.com/ru/post/1398515/


All Articles