一、场景说明:传递复杂对象(含嵌套对象+集合)并在HTML表格渲染

1. 定义复杂对象模型
// 商品类(嵌套对象)
public class Product {
private String productName;
private Double price;
// getter/setter
}
// 订单类(复杂对象,含集合+嵌套对象)
public class Order {
private String orderId;
private String userName;
private List<Product> productList; // 商品集合
  private Date createTime;
  // getter/setter
  }
2. 后端接口:模拟生成复杂订单数据并传递到页面
@Controller
@RequestMapping("/order")
public class OrderController {
// 模拟获取订单详情(含复杂对象)
@GetMapping("/detail")
public String getOrderDetail(Model model) {
// 构造嵌套商品对象
Product p1 = new Product("笔记本电脑", 5999.99);
Product p2 = new Product("无线鼠标", 129.99);
// 构造复杂订单对象
Order order = new Order();
order.setOrderId("ORD20250520001");
order.setUserName("张三");
order.setProductList(Arrays.asList(p1, p2));
order.setCreateTime(new Date());
// 传递复杂对象到Thymeleaf页面
model.addAttribute("order", order);
return "orderDetail"; // 跳转到orderDetail.html
}
// 接收前端提交的复杂订单数据(用于Postman测试)
@PostMapping("/submit")
@ResponseBody // 返回JSON便于Postman查看结果
public Order submitOrder(@RequestBody Order order) {
return order; // 直接返回接收的复杂对象
}
}

二、Thymeleaf页面:HTML表格渲染复杂对象数据

1. orderDetail.html代码
<!DOCTYPE html>
    <html xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8">
      <title>订单详情</title>
        <style>
          table {border-collapse: collapse; width: 80%; margin: 20px auto;}
          th, td {border: 1px solid #333; padding: 8px; text-align: center;}
          th {background-color: #f0f0f0;}
          .order-header {color: #0066cc;}
        </style>
      </head>
      <body>
      <h2 class="order-header" th:text="'订单详情:' + ${order.orderId}"></h2>
        <!-- 订单基础信息表格 -->
          <table>
            <tr>
            <th>用户名</th>
            <th>创建时间</th>
            </tr>
            <tr>
            <td th:text="${order.userName}"></td>
            <td th:text="${#dates.format(order.createTime, 'yyyy-MM-dd HH:mm:ss')}"></td>
            </tr>
          </table>
          <!-- 订单商品列表表格(遍历集合) -->
          <h3 class="order-header">商品清单</h3>
            <table>
              <tr>
              <th>商品名称</th>
              <th>价格(元)</th>
              </tr>
                <tr th:each="product : ${order.productList}">
              <td th:text="${product.productName}"></td>
              <td th:text="${#numbers.formatDecimal(product.price, 2, 2)}"></td>
              </tr>
            </table>
            <!-- 提交复杂对象的表单(可选) -->
                <form th:action="@{/order/submit}" method="post" enctype="application/json">
              <button type="button" onclick="submitOrder()">提交订单(测试用)</button>
              </form>
              <script>
                // 模拟前端构造复杂对象并提交(用于Postman测试参考)
                function submitOrder() {
                const order = {
                orderId: "ORD20250520002",
                userName: "李四",
                productList: [
                {productName: "手机", price: 3999},
                {productName: "耳机", price: 599}
                ],
                createTime: new Date().toISOString()
                };
                fetch("/order/submit", {
                method: "POST",
                headers: {"Content-Type": "application/json"},
                body: JSON.stringify(order)
                }).then(res => res.json()).then(data => console.log(data));
                }
              </script>
            </body>
          </html>
2. 页面效果图
  • 订单基础信息表格

    用户名创建时间
    张三2025-05-20 15:30:20
  • 商品清单表格

    商品名称价格(元)
    笔记本电脑5999.99
    无线鼠标129.99

三、Postman测试

1. 测试GET请求(获取复杂对象并渲染页面)
  • 请求地址http://localhost:8080/order/detail
  • 请求方式:GET
  • 响应:返回完整HTML页面(包含渲染后的表格数据),可在Postman的Preview标签查看页面效果。
2. 测试POST请求(提交复杂对象)
  • 请求地址http://localhost:8080/order/submit
  • 请求方式:POST
  • 请求头Content-Type: application/json
  • 请求体(Raw/JSON)
{
"orderId": "ORD20250520002",
"userName": "李四",
"productList": [
{"productName": "手机", "price": 3999},
{"productName": "耳机", "price": 599}
],
"createTime": "2025-05-20T16:00:00.000+08:00"
}
  • 响应结果:Postman返回提交的复杂对象JSON数据,验证后端成功接收:
{
"orderId": "ORD20250520002",
"userName": "李四",
"productList": [
{"productName": "手机", "price": 3999},
{"productName": "耳机", "price": 599}
],
"createTime": "2025-05-20T08:00:00.000+00:00"
}

四、关键知识点

  1. 复杂对象渲染

    • 嵌套对象属性通过 ${对象.嵌套对象.属性} 访问(如 ${product.productName})。
    • 集合遍历使用 th:each="元素 : ${集合}"(如遍历productList)。
    • 日期/数字格式化:Thymeleaf工具类#dates/#numbers处理格式(如#dates.format(...))。
  2. Postman测试要点

    • 提交JSON格式复杂对象时,需设置Content-Type: application/json
    • 集合参数需用JSON数组格式(如productList是数组)。
    • 后端接收复杂对象时,用@RequestBody注解(POST请求)或直接通过Model传递(GET请求)。
  3. 表格样式优化
    通过CSS设置表格边框合并、对齐方式、表头背景色等,提升可读性。

五、注意事项

  • 复杂对象传递时,确保属性名前后端一致(如productName而非productname)。
  • 日期类型传递需注意格式转换(Thymeleaf用#dates工具类,JSON用ISO格式)。
  • 若表格数据为空,可通过th:if="${not #lists.isEmpty(order.productList)}"做空值判断。