如何向后端服务返回对象列表?对于例如UI 中显示客户列表,其中只有用户选择的客户(选中复选框)应返回到后端( Controller 类)。但我无法返回所选对象。
我的代码:
public class CustomerType {
private String customerName;
private String customerMsg;
private Boolean selected;
// setter
// getter
}
public class Customers {
private ArrayList<CustomerType> customerType;
// setter
// getter
}
@GetMapping(value = "/")
public String index(ModelMap modelMap) {
ArrayList<CustomerType> customerType = new ArrayList<>();
customerType.add(new CustomerType("1", "c1", null));
customerType.add(new CustomerType("2", "c2", null));
customerType.add(new CustomerType("3", "c3", null));
Customers customers = new Customers();
customers.setCustomerTypes(customerType);
modelMap.put("customers", customers);
return "index";
}
@PostMapping(value = "/save")
public String save(@ModelAttribute Customers customers, BindingResult errors, Model model) {
...
...
return "hello";
}
========== index.html ==========
...
<form id = "form" class="col-xs-12 col-sm-4" role="form"
th:action="@{/save}" method="post" th:object="${customers}">
<div class="checkbox" th:each="customerType : ${customers.customerType}" >
<input type="checkbox" id="custType" name="custType"
th:text="${customerType.customerName}" th:value="${customerType.customerMsg}" th:checked="${customerType.selected}"></input>
</div>
<div>
<p>
<button type="submit" class="btn btn-default">Submit</button>
</p>
</div>
</form>
我能够在 UI 上显示客户列表,例如,如果用户选择 c1 和 c3,则有 3 个客户 c1、c2、c3,因此在单击提交按钮后,这些客户应该在保存方法中映射到 @ModelAttribute Customers 对象并且该对象应该包含两个对象 c1 和 c3 的列表,但我收到的是 Null,而不是 2 个对象。
我无法找到我出错的地方。
最佳答案
将表单发送回 Controller 时,请确保传输的数据反射(reflect)所需的对象结构。您必须提供与 CustomerType
对象的 checked
字段相对应的复选框以及与上述类的其他字段相对应的其他隐藏输入。
请将您的表单更新为如下所示:
<form id = "form" class="col-xs-12 col-sm-4" role="form" th:action="@{/save}" method="post" th:object="${customers}">
<div class="checkbox" th:each="customerType, iterator : ${customers.customerType}" >
<input type="hidden" th:field=*{customerType[__${iterator.index}__].customerName} />
<input type="hidden" th:field=*{customerType[__${iterator.index}__].customerMsg} />
<input type="checkbox" th:field="*{customerType[__${iterator.index}__].selected}" th:text="${customerType.customerName}" ></input>
</div>
<div>
<p>
<button type="submit" class="btn btn-default">Submit</button>
</p>
</div>
</form>
这样,您将收到 Customers
对象,其中包含所有传递的 CustomerType
对象的列表,其中 selected
字段的计算结果为 true 查看记录。
关于html - 如何使用 Thymeleaf 和 Spring Boot 将 UI 中的对象集合绑定(bind)到后端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47227789/