我正在尝试使用多个下拉菜单从 thymeleaf 传递产品 ID 列表。它输出尺寸,但产品对象为空。如果我创建List<String> product;
在Expense
类和替换expenseDetail
在addExpense.html
与 product
;有用。我正在尝试通过 ExpenseDetail
传递产品类
费用类别
@Entity
public class Expense {
//fields
@OneToMany(mappedBy = "expense", cascade = CascadeType.ALL)
@NotNull
private List<ExpenseDetail> expenseDetail;
//getters and setters
}
费用明细类
public class ExpenseDetail {
//fields
@ManyToOne
@JoinColumn(name = "expense_id")
private Expense expense;
@ManyToOne
@JoinColumn(name = "product_id")
private Product product;
//getters and setters
}
addExpense.html
<form th:action="@{/expense/new}" th:method="post" th:object="${expense}">
<select id="product" th:field="*{expenseDetail[0]}">
<option value="" th:text="#{item.select.prompt}"></option>
<option th:each="product: ${products}" th:value="${product.id}" th:text="${product.name}"></option>
</select>
<select id="product" th:field="*{expenseDetail[1]}" >
<option value="" th:text="#{item.select.prompt}"></option>
<option th:each="product: ${products}" th:value="${product.id}" th:text="${product.name}"></option>
</select>
<button type="submit" name="Save expense">Save Expense</button>
</form><!-- ends expense form -->
费用 Controller
@Controller
public class ExpenseController {
@PostMapping("/expense/new")
public String addExpense(@Valid Expense expense, BindingResult result, Model model){
//This prints the list of size 2
System.out.println(expense.getExpenseDetail().size());
List<ExpenseDetail> el=expense.getExpenseDetail();
el.forEach(e->{
System.out.println(e.getProduct()); //this is null
});
return "addExpense";
}
}
最佳答案
选择上的字段应该是您希望所选选项的值(产品 ID)所在的位置,因此您应该使用 th:field="*{expenseDetail[0].product.id}"
。
这将为您提供一个 Product
,其中包含 ExpenseDetail
对象中选定的 ID。如果在选择中没有选择任何内容,那么您最终会在 Product
中得到一个 null ID,您需要在服务器端处理这些问题,或者使用 JavaScript 来排除该字段(如果该字段为 null)。
请记住,Thymeleaf 不知道有关您的 Product
对象或其来源的任何信息。它只会填充表单中出现的字段,因此诸如 name
之类的其他内容在 POST 处理程序中将为 null。通常,您只需获取 ID 并使用它从数据库或其他任何位置重新加载对象。
关于java - 从 thymeleaf 到 spring boot 的对象列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43437498/