您需要应用一些基本的算术逻辑。检查以下实现。
由于我没有足够的 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>