【问题标题】:How to submit table data in Spring Thymeleaf如何在 Spring Thymeleaf 中提交表格数据
【发布时间】:2018-05-30 02:21:18
【问题描述】:

我正在按照给定的链接提交要保存在数据库中的表数据

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>

模型类:

public class Rule  {
  private Integer id;   
  private Date timestamp;   
  private String title; 
  private String body;  
  // constructor and Getter/Setters
}

表单类:

public class RuleForm { 
  private List<Rule> rule;
  public List<Rule> getRule() {
    return rule;
  }
  public void setRule(List<Rule> rule) {
    this.rule = rule;
  }
}

控制器方法:

@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";
}

请让我知道我缺少什么。

更新 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>

在页面加载时收到异常后进行这些更改。

org.springframework.expression.spel.SpelEvaluationException: EL1008E: 在“java.util.ArrayList”类型的对象上找不到属性或字段“规则” - 可能不是公共的?

请查看我在页面加载时发送模型属性“ruleForm”中的原始列表。一旦页面加载数据并且用户进行更改,我想将完整的表发布回控制器。

【问题讨论】:

标签: java spring spring-mvc thymeleaf


【解决方案1】:

表单应该有一个th:object,而不是th:field

<form method="POST" th:action="@{/updateAllRules}" th:object="${ruleForm}">

您应该使用th:field,而不是使用th:nameth:value,这两种方法都适合您。还应使用 *{...} 语法指定字段,该语法自动假定为 th:object

<input type="text" th:field="*{rule[__${iteration.index}__].title}" />

在我看来,其他一切都是正确的。

【讨论】:

  • 感谢您对此感兴趣。我按照您的建议进行了更改,但失败了。请参考更新 1。
猜你喜欢
  • 2014-06-17
  • 2021-01-28
  • 2019-01-19
  • 2019-03-29
  • 2019-11-27
  • 2015-09-03
  • 1970-01-01
  • 1970-01-01
  • 2021-05-05
相关资源
最近更新 更多