java - 百里香叶。th:each 不适用于模型属性
问题描述
我正在尝试List
使用 Thymeleaf 在我的浏览器中显示表单。这List
被分配给一个model
属性
@ModelAttribute("groups")
List<GroupReadModel> getGroups() {
return service.readAll();
}
这是GroupReadModel
:
public class GroupReadModel {
private int id;
private String description;
public GroupReadModel() {
}
public int getId() {
return id;
}
void setId(int id) {
this.id = id;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
我想要这个列表中每个项目的表单,所以我th:each
在我的模板中使用:
<dl th:each="existingGroup : ${groups}" th:id="${existingGroup.id}">
<dd>
<form method="post" th:action="@{/groups}" th:object="${existingGroup}">
<label>Group description
<input type="text" th:field="${existingGroup.description}" />
</label>
<button type="submit" name="updateGroup" th:value="${existingGroup.id}">UPDATE</button>
</form>
</dd>
</dl>
我在渲染时遇到的问题:
[THYMELEAF][http-nio-8080-exec-1] Exception processing template "groups": Error during execution of processor 'org.thymeleaf.spring5.processor.SpringInputGeneralFieldTagProcessor' (template: "groups" - line 63, col 44)
org.thymeleaf.exceptions.TemplateProcessingException: Error during execution of processor 'org.thymeleaf.spring5.processor.SpringInputGeneralFieldTagProcessor'
Caused by: java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'existingGroup' available as request attribute
这是第 63 行:<input type="text" th:field="${existingGroup.description}" />
我该怎么做才能使此代码正确?
解决方案
使用 时th:object
,您正在选择对象,您可以使用*{..}
语法来使用它。
替换th:field="${existingGroup.description}"
为th:field="*{description}"
和:th:value="${existingGroup.id}"
_th:value="*{id}"
<form method="post" th:action="@{/groups}" th:object="${existingGroup}">
<label>Group description
<input type="text" th:field="*{description}" />
</label>
<button type="submit" name="updateGroup" th:value="*{id}">UPDATE</button>
</form>
推荐阅读
- c - 两个程序之间的区别 - 在 file.c 中包含或不包含 file.h
- flutter - 如何用颤振密码保护文件
- python - 如何使用 Matplotlib 错误条图形进行绘图
- sympy - sympy.symbols 和 sympy.Symbol 之间的区别
- python - 如何使用 urllib3 发布 x-www-form-urlencoded 数据
- python - IDLE和python不同,无法正确安装模块
- google-apps-script - 开发一个日历和电子表格脚本的项目,可以吗?
- sql-server - 如何在 SQL Server 2017 中将列添加到复制表的主键
- python - Solr Prepared 语句,按数据中心进行工作负载隔离
- web-scraping - 从 HTML 网站提取或提取数据时出现 VBA 代码错误