Sac*_*yal 5 java spring spring-mvc thymeleaf
我正在按照给定的链接提交要保存在数据库中的表数据
http://viralpatel.net/blogs/spring-mvc-multi-row-submit-java-list/
但是给定链接和我的实现之间的区别在于,链接的前端使用 JSTL(JSP),而我使用的是 Thymeleaf(HTML)
以下是正在使用的文件
HTML 表单:
<form method="POST" th:action="@{/updateAllRules}" th:field="${ruleForm}">
<table>
<thead>
<tr>
<th>S No</th>
<th>Title</th>
<th>Body</th>
</tr>
</thead>
<tbody>
<tr th:each="ruleModel,iteration : ${allRules}">
<td th:text="${ruleModel.id}"></td>
<td><input type="text" th:name="${'rule'+iteration.index+'.title'}" th:value="${ruleModel.title}"></td>
<td><input type="text" th:name="${'rule'+iteration.index+'.body'}" th:value="${ruleModel.body}"></td>
</tr>
</tbody>
</table>
<br>
<input type="submit" value="Update All">
</form>
Run Code Online (Sandbox Code Playgroud)
模型类:
public class Rule {
private Integer id;
private Date timestamp;
private String title;
private String body;
// constructor and Getter/Setters
}
Run Code Online (Sandbox Code Playgroud)
表格类:
public class RuleForm {
private List<Rule> rule;
public List<Rule> getRule() {
return rule;
}
public void setRule(List<Rule> rule) {
this.rule = rule;
}
}
Run Code Online (Sandbox Code Playgroud)
控制器方法:
@RequestMapping(value = "/updateAllRules", method = RequestMethod.POST)
public String updateAllRules(@ModelAttribute("ruleForm") RuleForm ruleForm) throws IOException
{
System.out.println(ruleForm); // this prints com.web.model.RuleForm@235f9fcb
System.out.println(ruleForm.getRule()); //this prints null
return "redirect:/admin";
}
Run Code Online (Sandbox Code Playgroud)
请让我知道我缺少什么。
更新1:
按照建议进行了更改。我的新 HTML 表单如下
<form method="POST" th:action="@{/updateAllRules}" th:object="${ruleForm}">
<table>
<thead>
<tr>
<th>S No</th>
<th>Title</th>
<th>Body</th>
</tr>
</thead>
<tbody>
<tr th:each="rule,iteration : ${ruleForm}">
<td th:field="*{rule[__${iteration.index}__].id}"></td>
<td><input type="text" th:field="*{rule[__${iteration.index}__].title}"></td>
<td><input type="text" th:field="*{rule[__${iteration.index}__].body}"></td>
</tr>
</tbody>
</table>
<br>
<input type="submit" value="Update All">
</form>
Run Code Online (Sandbox Code Playgroud)
在页面加载时收到以下异常后进行这些更改。
org.springframework.expression.spel.SpelEvaluationException:EL1008E:在“java.util.ArrayList”类型的对象上找不到属性或字段“规则”——可能不是公开的?
请参阅我在页面加载时在模型属性“ruleForm”中发送原始列表。一旦页面加载了数据并且用户进行了更改,我想将完整的表 POST 回控制器。
表单应该有一个th:object,而不是th:field:
<form method="POST" th:action="@{/updateAllRules}" th:object="${ruleForm}">
Run Code Online (Sandbox Code Playgroud)
您应该使用 which 为您完成这两个操作,而不是使用and th:name。还应该使用自动假定的语法来指定字段。th:valueth:field*{...}th:object
<input type="text" th:field="*{rule[__${iteration.index}__].title}" />
Run Code Online (Sandbox Code Playgroud)
其他一切在我看来都是正确的。