我有一个时间条目列表,我想在我的页面中为其创建一个模式。 每次输入都会有它自己的模式。在这些模态中,我想放置一个表单。 每个表单必须指向一个时间条目支持 bean。
这是附加到此页面的端点的相关部分
@GetMapping("/time/{year}/{month}/{dayOfTheMonth}")
public String show(
ModelMap model,
@PathVariable Integer year,
@PathVariable Integer month,
@PathVariable Integer dayOfTheMonth
){
....
var editEntryForms = entries
.stream()
.map(EditEntryForm::new)
.collect(Collectors.toList());
model.addAttribute("editEntryForms", editEntryForms);
return "timesheet/show";
}
我的表单支持对象
@Data
class EditEntryForm {
public EditEntryForm(TimeEntry timeEntry){
id = timeEntry.getId();
description = timeEntry.getDescription();
}
private Long id;
private String description;
}
以及模板(的相关部分)
<div class="ui modal"
th:each="editEntryForm : ${editEntryForms}"
th:id="${'edit-entry-modal-'+editEntryForm.id}">
<div class="header">
Edit time entry
</div>
<div class="content">
<form class="ui form"
th:object="${editEntryForm}"
th:classappend="${#fields.hasErrors('*')} ? error"
th:id="${'edit-entry-form'+ editEntryForm.id}"
th:action="@{/time/{year}/{month}/{day}/{entryId}(year=${year}, month=${month}, day=${dayOfTheMonth}, entryId=${editEntryForm.id})}"
method="POST">
...
</form>
</div>
<div class="actions">
<button class="ui approve primary button" form="add-entry-form">Update entry</button>
<div class="ui cancel button">Cancel</div>
<div class="ui right floated basic button">
Delete
</div>
</div>
</div>
该表单在结果页面中可见,具有正确的 ID(根据 th:id="${'edit-entry-modal-'+editEntryForm.id}"
的要求),所以我假设我的绑定(bind)是正确的。
但是模板评估无法完成,出现以下错误
org.thymeleaf.exceptions.TemplateInputException: An error happened during template parsing (template: "class path resource [templates/timesheet/show.html]")
at
...
Caused by: java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'editEntryForm' available as request attribute
...
2020-05-15 09:19:47.449 ERROR 10251 --- [nio-9090-exec-2] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.thymeleaf.exceptions.TemplateInputException: An error happened during template parsing (template: "class path resource [templates/timesheet/show.html]")] with root cause
...
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'editEntryForm' available as request attribute
at org.springframework.web.servlet.support.BindStatus.<init>(BindStatus.java:153) ~[spring-webmvc-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at
您是否发现我做错了什么,或者这可能是我不知道的 Thymleaf 的限制。
最佳答案
尝试使用普通的 Java 数组,在 th:each
中的 Thymeleaf 中进行迭代。也许尝试类似 .toArray()
的东西上editEntryForms
因为它的类型应该是 List<>
。然后删除你的th:object
通知。现在您应该能够访问数组中所有项目的内容,就像您通常在 Thymeleaf 中一样。另请看一下我对我的问题的更新答案 https://stackoverflow.com/a/59703725/10112957
关于java - 将表单支持 bean 列表绑定(bind)到表单列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61820680/