您需要應用一些基本的算術邏輯。檢查下面的實施。
因爲我沒有足夠的JSTL經驗,我不得不使用JSP Scriptlets。
採樣輸入創建在控制器
// number of students
final int numStudents = 17;
String array[] = new String[s];
for (int i = 0; i < numStudents; i++) {
array[i] = "Student " + (i + 1);
}
List<String> students = Arrays.asList(array);
鑑於表創建代碼
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<c:if test="${not empty students}">
<c:set var="numStudents" value="${fn:length(students)}" />
<%-- Variable initialization, arithmetic operations --%>
<%
int numStds = Integer.valueOf("" + pageContext.getAttribute("numStudents"));
int numStdCol1, numStdCol2, numStdCol3;
numStdCol1 = numStdCol2 = numStdCol3 = numStds/3;
if (numStds % 3 == 1) {
numStdCol1 ++;
} else if (numStds % 3 == 2) {
numStdCol1 ++;
numStdCol2 ++;
}
pageContext.setAttribute("numCol1", numStdCol1);
pageContext.setAttribute("numCol2", numStdCol2);
pageContext.setAttribute("numCol3", numStdCol3);
%>
<%-- Table creation --%>
<table border="1" cellspacing="0" cellpadding="0">
<tr>
<c:forEach var="student" begin="0" end="${numCol1 - 1}" items="${students}">
<td>${student}</td>
</c:forEach>
</tr>
<tr>
<c:forEach var="student" begin="${numCol1}" end="${numCol1 + numCol2 - 1}" items="${students}">
<td>${student}</td>
</c:forEach>
</tr>
<c:forEach var="student" begin="${numCol1 + numCol2}" end="${numStudents - 1}" items="${students}">
<td>${student}</td>
</c:forEach>
</tr>
</table>
</c:if>
</body>
</html>
輸出爲樣本輸入
<table border="1" cellspacing="0" cellpadding="0">
<tr>
<td>Student 1</td>
<td>Student 2</td>
<td>Student 3</td>
<td>Student 4</td>
<td>Student 5</td>
<td>Student 6</td>
</tr>
<tr>
<td>Student 7</td>
<td>Student 8</td>
<td>Student 9</td>
<td>Student 10</td>
<td>Student 11</td>
<td>Student 12</td>
</tr>
<td>Student 13</td>
<td>Student 14</td>
<td>Student 15</td>
<td>Student 16</td>
<td>Student 17</td>
</tr>
</table>
由於Rupak。這很有幫助。 – Java4life