我有一个有关 GET
请求的记录列表,该列表通过复选框显示在 UI 上。
@GetMapping("/list")
public String list(Model model) {
model.addAttribute("records", createRecords());
return "list";
}
这是我的记录
POJO
:
class Record {
private boolean selected;
private Integer id;
private String name;
private String phone;
//....
我在 UI 中显示如下:
<th:block th:each = "record : ${records}">
<tr>
<td><input type="checkbox" th:field="*{selected}" th:checked="${record.selected}" /></td>
<td th:field="*{id}" th:text="${record.id}" />
<td th:field="${name}" th:text="${record.name}" />
<td th:field="${phone}" th:text="${record.phone}" />
</tr>
</th:block>
我很难从 UI
获取 POST
上所选记录的 List
。我刚刚从 POST
取回一个对象。
我想要在 POST
映射中进行类似的操作:
@PostMapping("/list")
public String select(@ModelAttribute ArrayList<Record> records) {
//... at least ids of selected records
//... or all the records back with selected
请帮忙。
最佳答案
导致您的问题的潜在原因有很多。下面列出的三项应该可以帮助您正确映射表单:
您应该正确构建表单,包括使用
*
减少重复的符号,例如:<th:block th:each = "record : ${records}"> <tr> <td><input type="checkbox" th:field="*{selected}"/></td> <td><input type="text" th:field="*{id}"/></td> <td><input type="text" th:field="*{name}"/></td> <td><input type="text" th:field="*{phone}"/></td> </tr> </th:block>
循环
${records}
时可能需要使用双下划线表示法得到每个Record
正确填写您的表格。根据the Thymeleaf + Spring tutorial :..
__${...}__
syntax is a preprocessing expression, which is an inner expression that is evaluated before actually evaluating the whole expression.例如参见this question .
仔细检查您是否在 Spring
@Controller
中正确处理结果列表。通过接受List<Record>
注释为@ModelAttribute
或@RequestParam
。 (看起来您已经在这样做了。)例如参见this question .
关于java - Spring 启动: How to bind list of objects on POST in thymleaf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46250899/