java - Spring MVC 和 Thymeleaf - 之间有什么区别 :value and th:field when you iterate multiple items?

标签 java spring thymeleaf

我想使用 HTML 表单将多个项目从数据库显示到 Thymeleaf View ,以便我可以对数据库进行更改和更新。

我打算使用 th:field 。但发生了错误。当我尝试使用th:value时。并且它显示数据。

<div th:each="item : ${courses}">
  <form th:object="${item}">
    <input th:field="*{name}" type="text" id="name" name="name" /> // error occur
  </form>
</div>

以下错误。

Neither BindingResult nor plain target object for bean name 'item' available as request attribute

而下面的代码工作正常。

<div th:each="item : ${courses}">
  <form th:object="${item}">
    <input th:value="*{name}" type="text" id="name" name="name" /> // ok
  </form>
</div>

我走在正确的道路上吗?你能解释一下为什么吗?字段和值之间的区别?

最佳答案

底线是您只能使用 th:objectth:field一起在基本模型属性上。这意味着您在迭代时无法使用它(因为模型中不存在 ${item} ,它是由 th:each 生成的变量)。要求已详细说明here :

Values for th:object attributes in form tags must be variable expressions (${...}) specifying only the name of a model attribute, without property navigation. This means that an expression like ${seedStarter} is valid, but ${seedStarter.data} would not be.

Once inside the <form> tag, no other th:object attribute can be specified. This is consistent with the fact that HTML forms cannot be nested.

th:field设置name , id ,和value一个字段的。因此它们在某种程度上可以互换,但您应该使用 th:field只要有可能,因为它提供了与 spring 的额外集成,并且适用于所有类型的输入 - 但这些实际上仅在您编辑页面上的单个对象时才有用。

由于您要迭代多个对象,因此您必须手动设置 name , id ,和value就像你正在做的那样。

关于java - Spring MVC 和 Thymeleaf - 之间有什么区别 :value and th:field when you iterate multiple items?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54677313/

相关文章:

java - Jasper Report 生成 PDF,然后 Glassfish 崩溃/关闭

Java Swing 更新 JTextArea 中的字符串

java - 在 Spring 中设置 GOOGLE_APPLICATION_CREDENTIALS

spring-boot - 如何在 thymeleaf 模板名称处发送 html 内容

java - 将字符串转换为多维数组

java - 我怎样才能让一个java程序分段下载自己然后运行?

java - 如何将html输入值从表单传递到数据库(Springboot)

spring - 如何在 Spring Boot 中为每个主题动态创建单独的 Kafka 监听器?

spring-mvc - 使用 Thymeleaf 的 "application-specific"在 Web UI 中显示 "fields.hasErrors"验证错误

java - 如何对 spring datetimeformat 验证进行单元测试