【问题标题】:THYMELEAF. th:each doesn't work for model attribute百里香叶。 th:each 不适用于模型属性
【发布时间】:2021-08-01 08:07:48
【问题描述】:

我正在尝试使用 Thymeleaf 在我的浏览器中显示 List 的表单。这个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 行:&lt;input type="text" th:field="${existingGroup.description}" /&gt; 我该怎么做才能使这段代码正确?

【问题讨论】:

  • groups.html 中的第 63 行是哪一行? th:id="${existingGroup.id}" 无法工作,因为 GroupReadModel 类中没有 id 属性。还有th:value="${taskStat.index + 1}" -> taskStat 应该从哪里来?
  • 很抱歉在我的问题中犯了一些错误。现在应该没问题了。错误还是一样。

标签: java spring-boot templates thymeleaf


【解决方案1】:

当您使用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>

【讨论】:

  • 不幸的是它仍然无法正常工作并在同一行抛出相同的错误
猜你喜欢
  • 1970-01-01
  • 2017-12-22
  • 2015-11-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-14
  • 1970-01-01
相关资源
最近更新 更多