我想知道,列表如何在 Spring 中绑定(bind)......以及如何在 Thymeleaf 中访问它们。 有和没有 WrapperClass 如何实现通过表单向ArrayList或普通Array添加单个/多个对象..
非常感谢您的解释。
这就是我尝试过的: 表格
<form action="#" th:action="@{/tests}" th:object="${features}" method="post">
<input type="text" th:field="*{featureArrayList[0].name}"/>
<input type="text" th:field="*{featureArrayList[1].name}"/>
<p><input type="submit" value="Submit" /> <input type="reset" value="Reset" /></p>
</form>
包装类
ArrayList<Feature> featureArrayList = new ArrayList<Feature>();
public FeatureWrapper() {
}
public ArrayList<Feature> getFeatureArrayList() {
return featureArrayList;
}
public void setFeatureArrayList(ArrayList<Feature> featureArrayList) {
this.featureArrayList = featureArrayList;
}
型号:
private String name;
public Feature(String name) {
this.name = name;
}
public Feature() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
Controller
@GetMapping("/tests")
public String showForm(Model model)
{
FeatureWrapper featureWrapper = new FeatureWrapper();
model.addAttribute("features", featureWrapper);
return "Feature";
}
@PostMapping("/tests")
public String proceedForm(@ModelAttribute("features") FeatureWrapper features,Model model)
{
for(Feature feature: features.getFeatureArrayList())
{
System.out.println(feature.getName());
System.out.println(features.getFeatureArrayList().size());
}
return "Feature";
}
编辑1: 现在它使用包装类并使用静态索引...... 如果没有包装类,我如何实现这一点,我读了很多关于 EL 表达式 ${var.index} 的内容,但是它是如何工作的? 我应该如何使用它来动态添加我的对象。 Edit2:现在我可以将单个对象和多个对象添加到列表中,但我没有使用任何 EL 表达式,所以我想知道 我什么时候需要使用这样的东西:
<div th:each="feature,stat:*{featureArrayList}">
<input id="myInput" type="text" th:field="*{featureArrayList[__${stat.index}__].name}"/>
</div>
最佳答案
据我所知,如果没有包装类,则无法绑定(bind)到列表(如评论中所述)。
在普通的Thymeleaf表达式中,你可以直接使用变量作为索引。例如这样的表达式:
<th:block th:with="i=0"> <span th:text="${array[i]}" /> </th:block>
但是,th:field 表达式不同。如果您阅读有关 dynamic fields 的部分:
The problem is that Spring EL does not evaluate variables inside array index brackets, so when executing the above expression we would obtain an error telling us that
rows[rowStat.index]
(instead ofrows[0]
,rows[1]
, etc) is not a valid position in the rows collection. That’s why preprocessing is needed here.因此,当您使用
th:field
将输入绑定(bind)到数组时,您必须使用预处理,这就是为什么您会看到如下表达式:<input type="text" th:field="*{featureArrayList[__${stat.index}__].name}"/>
关于javascript - 通过表单提交创建ArrayList(Thymeleaf + Spring MVC),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55632147/