Spring Boot 1.5.4
我需要在POST方法中使用List<OrderTo>
。
的Controler:
@PostMapping("/orderlist")
public String confirmOrder(
, @RequestParam(name = "id", required = false) List<Integer> idL
, @RequestParam(name = "selected", required = false) List<Integer> selectedL
, @RequestParam(name = "typeName", required = false) List<String> typeNameL
// ...another Lists
// ,@ModelAttribute List<OrderTo> notWork
) {
// Collect All Lists
我找到的最佳选择是带有类字段的列表。也许我错过了什么。
查看:
<form action="orderlist" method="POST" id="catalogform">
<table class="table table-hover table-bordered table-striped table-condensed">
<tr>
<th><#--...--></th>
</tr>
<#list coffeetypelist as type> <#--Freemarker-->
<tr>
<td>
<input type="hidden" name="id" value="${type.id}">
<input type="checkbox" name="selected" value="${type.id}" >
</td>
<td><input type="hidden" name="typeName" value="${type.typeName}">${type.typeName}</td>
<td><input type="hidden" name="price" value="${type.price}">${type.price} TGR</td>
<td><input type="number" size="3" name="quantity" min="0" step="1"/></td>
</tr>
<#--...-->
</#list>
<#--...-->
型号:
public class OrderTo{
private int id;
private String typeName;
private int quantity;
private Double price;
private boolean selected;
//+constructors +getters + setters
这是否可以在没有额外收集操作的情况下获取List?如何?
答案 0 :(得分:0)
感谢shantaram_t的思考方向。关键是我们需要一个包装类。
public class OrderToWraper {
@Valid
@NotNull
private List<OrderTo> items;
之后,控制器可以使用有效的OrderToWraper对象:
@PosttMapping("/orderlist")
public String confirmOrder(@Valid OrderToWraper orderToWraper, BindingResult result, ModelMap map) {
if (result.hasErrors()) {
//...
使用freerarker进行列表绑定时有一些非显而易见的时刻(<@spring.formInput>
不起作用)
<#list orderToWraper.items as type>
<tr>
<td>
<@macros.textInputHidden "orderToWraper.items[${type_index}].id"/>
<input type="checkbox" name="items[${type_index}].selected" value="true">
</td>
<td><@macros.textInputHidden "orderToWraper.items[${type_index}].typeName"/>${type.typeName}</td>
<td><@macros.textInputHidden "orderToWraper.items[${type_index}].price"/>${type.price}</td>
<td><@macros.textInput "orderToWraper.items[${type_index}].quantity" "class='form-control'"/></td>
<td><@macros.showErrors "<br>" "text-danger"/></td>
</tr>
</#list>
freemarker macro:
<#macro textInputHidden path>
<@spring.bind path/>
<#assign id="${spring.status.expression?replace('[','')?replace(']','')}">
<input type="hidden" id="${id}" name="${spring.status.expression}" value="${spring.stringStatusValue}">
<#nested>
</#macro>