【问题标题】:Spring Boot : How to bind list of objects on POST in thymleafSpring Boot:如何在 thymeleaf 中绑定 POST 上的对象列表
【发布时间】:2018-02-25 07:33:13
【问题描述】:

我有一个关于GET 请求的记录列表,它显示在 UI 上并带有一个复选框。

@GetMapping("/list")
public String list(Model model) {
    model.addAttribute("records", createRecords());
    return "list";
}

这是我的RecordPOJO

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

请帮忙。

【问题讨论】:

标签: java spring-mvc spring-boot thymeleaf


【解决方案1】:

您的问题有多种潜在原因。下面列出的三个项目应该可以帮助您正确映射表单:

  1. 您应该正确构建表单,包括使用* 符号来减少重复,例如:

    <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>
    

    Spring + Thymeleaf tutorial所示

  2. 在循环${records} 时,您可能需要使用双下划线符号来正确填写表单中的每个Record。根据the Thymeleaf + Spring tutorial

    ..__${...}__ 语法是一个预处理表达式,它是一个在实际计算整个表达式之前先计算的内部表达式。

    参见例如this question

  3. 通过接受带有@ModelAttribute@RequestParam 注释的List&lt;Record&gt;,仔细检查您是否在Spring @Controller 中正确处理了结果列表。 (您似乎已经在这样做了。

    参见例如this question

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-12
    • 2016-07-13
    • 2016-02-17
    • 2020-01-04
    • 2018-12-11
    • 2020-09-09
    • 2018-04-23
    相关资源
    最近更新 更多