繁体   English   中英

对象列表从百里香叶到春季靴子

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM