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

Spring Boot中Thymeleaf遍历嵌套对象列表渲染表格问题

问题根因

原代码无法正常渲染由三个核心问题导致:

  • HTML表格嵌套规则违规:<tr>标签不支持直接嵌套<tr>子元素,浏览器解析时会自动错位重排标签结构,直接导致Thymeleaf循环的作用域完全混乱
  • 循环层级冗余:listaUsuariosAD本身就是usuarioAD类型的LinkedList集合,不需要额外嵌套一层循环遍历
  • 结构不匹配:服务名称行仅占用1个单元格,和表头4列的宽度结构不匹配,会出现排版错乱;同时存在属性拼写错误,描述字段descripion拼写少写字符,会导致取值为空。
可直接运行的修正代码

使用Thymeleaf原生的<th:block>虚拟标签作为循环容器,该标签不会在最终渲染结果中生成实际HTML元素,完美适配表格这类有严格嵌套要求的结构:

<table class="table table-hover">
    <thead class="thead-light">
        <tr>
            <th scope="col">Usuario</th>
            <th scope="col">Teléfono</th>
            <th scope="col">mail</th>
            <th scope="col">Descripción</th>
        </tr>
    </thead>
    <tbody>
        <th:block th:each="servicio : ${objetos_Servicios}">
            <!-- 服务名单独占一行,跨4列适配表头,可按需添加样式区分 -->
            <tr>
                <td colspan="4" class="font-weight-bold bg-light" th:text="${servicio.servicio}"></td>
            </tr>
            <!-- 直接遍历当前服务关联的用户列表,逐行渲染数据 -->
            <tr th:each="usuario : ${servicio.listaUsuariosAD}">
                <td th:text="${usuario.usuario}"></td>
                <td th:text="${usuario.telefono}"></td>
                <td th:text="${usuario.mail}"></td>
                <td th:text="${usuario.descripcion}"></td>
            </tr>
        </th:block>
    </tbody>
</table>
关键实现说明
  • 不要用<tr>嵌套<tr>的写法实现分组循环,<th:block>是Thymeleaf处理这类结构化标签循环的标准方案
  • 服务名称行添加colspan="4"属性让单元格横跨整行,和表头列数对齐,避免排版错位
  • 删除原代码中多余的中间循环层,直接遍历listaUsuariosAD即可拿到每个用户对象
  • 修正原代码中描述字段的拼写错误,确保属性名和usuarioAD实体类的字段名完全一致

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 03:39:35