首页 > 解决方案 > 百里香叶。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}" /> 我该怎么做才能使此代码正确?

标签: javaspring-boottemplatesthymeleaf

解决方案


使用 时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>

推荐阅读