【问题标题】:Object list from thymeleaf to spring boot从 thymeleaf 到 Spring Boot 的对象列表
【发布时间】:2017-09-12 05:54:08
【问题描述】:

我正在尝试通过使用多个下拉菜单从 thymeleaf 传递产品 ID 列表。它输出大小,但产品对象为空。如果我在Expense 类中创建List<String> product; 并将addExpense.html 中的expenseDetail 替换为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
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";
    }
}

【问题讨论】:

    标签: java spring-mvc spring-boot thymeleaf


    【解决方案1】:

    select 上的字段应该是您希望所选选项(产品 ID)的值所在的位置,因此您应该使用 th:field="*{expenseDetail[0].product.id}"

    这将为您提供一个 Product,其中包含您的 ExpenseDetail 对象中的选定 ID。如果在选择中未选择任何内容,那么您最终将在Product 中得到一个空 ID,您需要在服务器端处理这些,或者如果该字段为空,则使用 JavaScript 排除该字段。

    请记住,Thymeleaf 对您的 Product 对象或它们的来源一无所知。它只会填充表单中出现的字段,因此在 POST 处理程序中,name 等其他内容将为空。通常,您只需获取 ID 并使用它从您的数据库或其他任何地方重新加载对象。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-15
      • 2021-08-01
      • 1970-01-01
      • 2018-02-25
      • 2017-10-20
      • 2020-10-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多