在我的网站上,我有几个复选框,每个复选框都包含 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/