spring - 使用spring mvc处理thymeleaf中的一对多关系
问题描述
我有一个实体作为供应商,另一个实体作为地址,它们之间的关系是一对多形式的供应商到地址。
注意:我正在使用 JPA
我的供应商实体
public class Vendor {
private Integer id;
private String name;
private List<Address> address;
// getter and setters
}
地址类:
public class Address {
private Integer id;
private String addressline1;
private String addressline2;
//getter and setters
}
现在我正在使用 Thymeleaf ,我有一个场景,我需要将地址动态添加到特定供应商的表单中。
如何使用 Spring mvc 中的 Thymeleaf 对供应商中的地址对象进行对象绑定?
解决方案
呃,这很棘手,因为绑定到表单不能以动态方式工作。这意味着你不能做像@Viergelenker 建议的事情并将每个地址对象绑定到他自己的形式。
您可以将单个地址对象添加到模型中,例如
model.addAttribute("address", addressObject); // Snippet for Model-object
modelAndView.addObject("address", addressObject); // Snippet for ModelAndView object
然后在你的模板中定义一个表单,如:
<form .... method=".." th:object="${address}">
<input type="hidden" th:field="*{id}" >
<input type="text" th:field="*{addressline1}" >
<input type="text" th:field="*{addressline2}" >
</form>
不幸的是,不可能将数组或列表添加到模型中并将该集合中的每个对象绑定到他自己的形式:
/* The following code doesn't work */
<th:block th:each="address : ${addresses}">
<form .... method=".." th:object="${address}">
<input type="text" th:field="*{addressline1}" >
...
</form>
</th:block>
或者
/* The following code doesn't work */
<th:block th:each="address, stat : ${addresses}">
<form .... method=".." th:object="${addresses[__stat.index__]}">
<input type="text" th:field="*{addressline1}" >
...
</form>
</th:block>
您可以做的是不使用表单绑定,而只是从没有绑定的表单中发送一些名称-值对(仅使用名称和 th:value 属性,而不是表单中的 th:field 属性)到控制器,获取它们来自 HttpServletRequest 对象并创建/更新/删除地址对象...或将整个 Vendor 对象绑定到一个表单(注意使用 stat.index):
<form th:object="${vendor}">
<input type="hidden" th:field="*{id}">
<input type="hidden" th:field="*{name}"> // feel free to make that field editable
<th:block th:each="addr, stat : *{address}">
<input type="hidden" th:field="*{address[__${stat.index}__].id}">
<input type="text" th:field="*{address[__${stat.index}__].addressline1}">
<input type="text" th:field="*{address[__${stat.index}__].addressline2}">
</th:block>
</form>
推荐阅读
- python - 由于 python-ldap 先决条件失败(Windows Active Directory),Flask-SimpleLDAP 无法安装
- excel - 使用 VBA 宏转换 Excel 日期列?
- grafana-variable - Grafana 仪表板:仪表板上的变量未显示所有值
- python - Plotly 图形对象中线的离散色标(Python)
- django - 无法从基于类的视图 Django 执行条件重定向
- flutter - 在屏幕之间传递数据而不在颤动中更改屏幕
- php - 我正在尝试使用 php 将自定义产品/价格添加到 Stripe 结帐页面
- regex - 熊猫使用正则表达式从字符串列中提取子字符串
- laravel - 如何在 Laravel 上显示 DigitalOcean 私人空间的临时 URL?
- linux - 如何仅在失败时重新启动 Systemd 服务?