【发布时间】:2026-01-16 22:10:02
【问题描述】:
我想将两个对象从 thymeleaf 形式传递给控制器。这是我的百里香代码:
<!DOCTYPE html>
<html lang='en' xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="ISO-8859-1"/>
<title>Payment Page</title>
</head>
<body>
<h1>Payment List</h1>
<table>
<tr>
<th>StuId</th>
<th>Month</th>
<th>Amount</th>
</tr>
<tr th:each="payment:${student.payments}">
<td th:text="${student.id}">2</td>
<td th:text="${payment.month}">devesh</td>
<td th:text="${payment.amount}">23</td>
</tr>
</table>
<h3>Add a Payment</h3>
<form action="#" th:action= "@{/payments}" th:object="${payment}" method="POST">
<div th:object="${student}" >
<label for="name">Month:</label>
<input type="text" name="month" size="50"></input><br/>
<label for="amount">Amount:</label>
<input type="text" name="amount" size="50"></input><br/>
<input type = "submit"/></form>
</body>
</html>
除了实际在此处提交的付款对象之外,我想将学生对象或 ID 传递给我的控制器,因为任何付款都应对应于特定学生。经过大量搜索,我到现在都找不到任何方法。
我想传递对象的PaymentController方法,因为我正在使用提交表单,我无法在th:action中传递变量
@RequestMapping(method = RequestMethod.POST, value = "/{id}/payments")
public String doPayment(@ModelAttribute("payment") PaymentRecord paymentRecord, @PathVariable int id) {
Student st = studentService.getStudentInfo(id);
st.addPayments(paymentRecord);
System.out.println("entered into do payment");
studentService.addStudent(st);
paymentService.doPayment(paymentRecord);
return "redirect:{id}/payments";
}
请提出建议。我被困在这里了
【问题讨论】:
-
您是否在表单标签中尝试过
<input type="hidden" name="studentId" th:value="${student.id}"? -
是的,我可以试试这个,但是之后如何在我的控制器中获取这个 id,我的意思是它是来自模型参数还是我需要在我的控制器方法签名中显式添加一个参数?抱歉,实际上这是我在 Spring Boot 中的第一个 Web 应用程序,所以我有很多问题:)
标签: html spring spring-boot spring-mvc thymeleaf