You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用JSTL c:forEach将2列50行表格转换为4列25行表格

实现步骤

你只需要将原有的单组循环逻辑改成按偏移量同时取前后两半数据的逻辑即可,具体实现如下:

  1. 先引入JSTL函数标签库,用于获取集合总长度
  2. 计算集合拆分的中间位置,自动适配总条数奇偶场景
  3. 每行同时输出前半段第i条、后半段第i+偏移量条数据,实现左右两组并排展示

完整代码示例:

<!-- 顶部先引入JSTL标签库(如果已有可以省略) -->
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>

<table class="table table-striped">
    <tr>
        <th>State Name</th>
        <th>Number of users</th>
        <th>State Name</th>
        <th>Number of users</th>
    </tr>
    <!-- 计算总条数和拆分偏移量 -->
    <c:set var="totalCount" value="${fn:length(stateuserCount)}"/>
    <c:set var="splitOffset" value="${(totalCount + 1) / 2}"/>
    <!-- 循环半段长度,每行同时输出左右两组数据 -->
    <c:forEach begin="0" end="${splitOffset - 1}" var="index">
        <tr>
            <!-- 左侧:前半段数据 -->
            <td>${stateuserCount[index].stateName}</td>
            <td>${stateuserCount[index].appCount}</td>
            <!-- 右侧:后半段数据,加越界判断兼容奇数总条数 -->
            <c:if test="${index + splitOffset < totalCount}">
                <td>${stateuserCount[index + splitOffset].stateName}</td>
                <td>${stateuserCount[index + splitOffset].appCount}</td>
            </c:if>
            <c:if test="${index + splitOffset >= totalCount}">
                <td></td>
                <td></td>
            </c:if>
        </tr>
    </c:forEach>
</table>

如果需要中文表头,将<th>里的英文替换为「州名」「用户数量」即可。如果你的数据固定是50条,拆分偏移量固定是25,也可以直接把splitOffset硬编码为25,不需要动态计算,逻辑完全一致。

内容的提问来源于stack exchange,提问作者MR_AD

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 08:36:00