java - 绑定(bind)列表或数组以在 Thymeleaf 中形成

标签 java html spring spring-boot thymeleaf

在我的网站上,我有几个复选框,每个复选框都包含 value 中的 id属性。提交表单后,我想要一个列表,其中包含要传递给 Controller ​​的已选中复选框的 ID。这就是我想制作比较 n 种产品的新页面的方式。

Controller 可以接受List<Long>long[] .这就是我现在所拥有的:

HTML:

<form th:action="@{/comparison}" th:object="${productsComparison}" target="_blank" method="post">
<table>
  <tr data-th-each="item, iter : ${items.item}">
    <td>
      <input type="checkbox" th:name="|productsComparison.ids[${iter.index}]|" th:value="${item.id}"/>
    </td>
  </tr>
</table>

我已经添加到我的 Controller List<Long>包裹在 ProductComparison使用适当的 setter和getter 。提交表单列表后始终为 null

Controller :

@RequestMapping("/productsPage")
public String showProducts(Model model) {
    ProductsComparison productsComparison = new ProductsComparison();
    model.addAttribute("productsComparison", productsComparison);
}

@RequestMapping("/comparison")
public String compareProducts(@ModelAttribute ProductsComparison productsComparison) {
    System.out.println("List: " + productComparison.getIds());
    // Always shows null
    return "comparison";
}
public class ProductsComparison {
    private List<Long> ids;
    // Getters & setters
}

最佳答案

下划线 __ 是 ThymeLeaf 的预处理表达式语法。或者通俗地说,下划线内的内容先于表达式的其余部分处理。

这很重要,因为您的表达式正在使用一个数组,并且它的 ${iter.index} 部分给出了数组索引。

如果您好奇或者是否有人偶然发现了这一点。 th:name 与 html 属性 name 没有什么不同。 ThymeLeaf 引擎只会将名称属性插入 html 实体或覆盖旧的。 ThymeLeaf 有很多属性,例如 this . th:field 是一个完全不同的野兽。它告诉 ThymeLeaf 将您的表单输入绑定(bind)到后面形成的 bean 或您的模型属性 th:object="${productsComparison}"。因此,使用表达式 th:field="*{ids[__${iter.index}__]}",Thymeleaf 将调用 productsComparison.getIds[0]和相应的二传手。

注意 th:name 如果您使用任何类型的 Javascript 提交,您可能想要使用它。您很可能正在序列化您的表单,并且此方法调用创建的 JSON 将使用 name 属性。

如果您想了解有关 ThymeLeaf 预处理表达式的更多信息,documentation 中有一些内容关于它。

关于java - 绑定(bind)列表或数组以在 Thymeleaf 中形成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44415339/

相关文章:

java - Kotlin 获取类型为字符串

java - 我如何预测何时会耗尽内存

javascript - 如何使用 initSelection 附加 jquery select2 值

java.lang.SecurityException : No active admin owned by uid 10047 for policy #4 on wipe data

java - 在我的 xhtml 中使用模板 (jsf) 后,commandLink 和 CommandButton 标记不会调用任何操作

css - Span 元素在 Windows 8 上的 Chrome 中未正确对齐

html - div 类的最后一个 child

使用 spring @Transactional 的 Spring Boot 无需启用事务管理即可工作

java - Springframework创建bean时出错

java - 对于 JDBC 操作,Spring 是否过于复杂?