[英]Object list from thymeleaf to spring boot
我正試圖通過使用多個下拉菜單從百萬富翁那里傳遞產品ID列表。 它輸出大小但產品對象為null。 如果我創建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
}
ExpenseDetail類
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 -->
ExpenseController
@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";
}
}
select上的字段應該是您想要所選選項(產品ID)的值的位置,因此您應該使用th:field="*{expenseDetail[0].product.id}"
。
那么這會給你一個Product
包含的范圍內選擇的ID ExpenseDetail
對象。 如果在選擇中沒有選擇任何內容,那么您將在Product
空ID,您需要在服務器端處理這些ID,或者如果字段為空則使用JavaScript來排除該字段。
請記住,Thymeleaf對您的Product
對象或其來源不了解。 它只會填充表單中出現的字段,因此在POST處理程序中其他類似name
將為null。 通常,您只需獲取ID並使用它從數據庫或其他任何方面重新加載對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.