java - 从 thymeleaf 到 spring boot 的对象列表

标签 java spring-mvc spring-boot thymeleaf

我正在尝试使用多个下拉菜单从 thymeleaf 传递产品 ID 列表。它输出尺寸,但产品对象为空。如果我创建List<String> product;Expense类和替换expenseDetailaddExpense.htmlproduct ;有用。我正在尝试通过 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/

相关文章:

java - 如何使用 Java 8 确定给定的周和年的天数

amazon-web-services - AWS Fargate 无法通过负载均衡器/公共(public) IP 访问 dockerized spring boot 应用程序

java - 在 Spring Boot JPA 中使用 Hibernate 过滤器

java - spring mvc 中的每个请求是否都创建了一个新的 bean 对象?

spring - 如何将动态值设置为@PropertySource?

spring-boot - 如何使用管理客户端访问keycloak?

Java网络应用程序: How to identify this memory issue?

java - 如何使用输入输出字符串中的 5 个字符并将它们间隔开

java - 输入类型数字和数字的值相乘

java - 为什么spring boot war不生成web.xml