【发布时间】:2018-04-23 23:28:52
【问题描述】:
如何将对象列表返回给后端服务?例如UI 中显示了客户列表,其中只有用户选择的客户(选中复选框)应返回到后端(控制器类)。但我无法返回所选对象。
我的代码:
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,则其中有三个客户 c1、c2、c3,因此在单击提交按钮后,它们应该在保存方法中映射到 @ModelAttribute 客户对象并且该对象应该包含两个对象 c1 和 c3 的列表,但我收到的不是 2 个对象。
我不知道哪里出错了。
【问题讨论】:
-
你能分享你的 Thymeleaf 模板吗?
-
thymeleaf.org">
客户类型
标签: html spring user-interface spring-boot thymeleaf