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

如何通过Thymeleaf点击按钮将表格行数据传递至Spring Controller

实现Thymeleaf表格行数据传递到Spring Controller

问题场景

已通过Thymeleaf渲染出书籍信息表格,需求是点击每行的Order按钮时,将该行对应的书籍数据传递至Spring Controller中。

现有代码

前端Thymeleaf代码

<thead>
    <tr>
        <th>Company Name</th>
        <th>Book Name</th>
        <th>Author</th>
        <th>Price</th>
        <th>Order</th>
    </tr>
</thead>
<tbody>
<tr th:each="Books: ${Books }">
    <td th:text="${Books.CompanyName}" />
    <td th:text="${Books.BookName}" />
    <td th:text="${Books.AuthorName}" />
    <td th:text="${Books.Price}" />
    <td th:button class="Order-Button" type="button" >Order</button> </td>

后端Spring Controller代码

@Autowired
private BookRep bookRep;

@RequestMapping(value = "/BookOrder")
ModelAndView submitBookOrder(){
    ModelAndView mav = new ModelAndView("BookOrder");
    mav.addObject("Books", bookRep.findAll());
    return mav;
}

解决方案

前端修改(两种常用实现方式)

方式1:表单提交传递书籍主键

通过隐藏表单提交书籍ID,Controller后续通过ID查询完整数据:

<tbody>
<tr th:each="book : ${Books}">
    <td th:text="${book.CompanyName}" />
    <td th:text="${book.BookName}" />
    <td th:text="${book.AuthorName}" />
    <td th:text="${book.Price}" />
    <td>
        <form th:action="@{/submitOrder}" method="post">
            <input type="hidden" th:value="${book.id}" name="bookId" />
            <button class="Order-Button" type="submit">Order</button>
        </form>
    </td>
</tr>
</tbody>

方式2:AJAX异步传递完整数据

适合无需页面跳转的场景,直接传递整行书籍数据:

<tbody>
<tr th:each="book : ${Books}">
    <td th:text="${book.CompanyName}" />
    <td th:text="${book.BookName}" />
    <td th:text="${book.AuthorName}" />
    <td th:text="${book.Price}" />
    <td>
        <button class="Order-Button" type="button" 
                th:data-book="${book}" onclick="submitOrder(this)">Order</button>
    </td>
</tr>
</tbody>

<script>
function submitOrder(btn) {
    const bookData = JSON.parse(btn.dataset.book);
    fetch('/submitOrder', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(bookData),
    })
    .then(response => response.text())
    .then(data => {
        console.log('提交结果:', data);
        // 可添加成功提示或页面逻辑
    });
}
</script>

后端Controller修改

对应方式1(接收主键):

@Autowired
private BookRep bookRep;

// 原页面查询接口
@RequestMapping(value = "/BookOrder")
ModelAndView showBookOrder(){
    ModelAndView mav = new ModelAndView("BookOrder");
    mav.addObject("Books", bookRep.findAll());
    return mav;
}

// 新增订单提交接口
@PostMapping("/submitOrder")
public String handleOrderSubmit(@RequestParam("bookId") Long bookId) {
    Book book = bookRep.findById(bookId).orElse(null);
    // 此处执行业务逻辑,如创建订单
    return "redirect:/orderSuccess"; // 跳转成功页或其他页面
}

对应方式2(接收完整Book对象):

// 新增接收JSON格式数据的接口
@PostMapping("/submitOrder")
@ResponseBody
public String handleOrderSubmit(@RequestBody Book book) {
    // 直接获取完整书籍数据,执行业务逻辑
    System.out.println("收到订单书籍:" + book.getBookName());
    return "订单提交成功";
}

注意:确保Book实体类有完整的Getter/Setter方法,字段名与前端传递的键名一致,Spring才能完成数据映射。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 19:40:31