java - Spring 启动: How to bind list of objects on POST in thymleaf

标签 java spring-mvc spring-boot thymeleaf

我有一个有关 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

请帮忙。

最佳答案

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

  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 :

    ..__${...}__ syntax is a preprocessing expression, which is an inner expression that is evaluated before actually evaluating the whole expression.

    例如参见this question .

  3. 仔细检查您是否在 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/

相关文章:

Java - 声明数组

eclipse - Spring Web-用 WebApplicationInitializer 替换 web.xml 给我 404

java - 在 Spring MVC 中使用@JsonView

java - Spring MVC - HTTP 状态 404

java - 使用泛型类型编写 HQL UPDATE 查询

java - 如何从 spring-boot 执行 postgres sql block

java - Maven - ClassNotFoundException : org. apache.commons.lang.StringUtils

java - Exchange 日历、创建约会和唯一 ID

java - 如何在 AIX 中运行 jar 文件?

java - Spring boot应用程序在STS中运行失败,但在命令行上运行正常