因此,我将一个
Map<Category, List<Product>>
传递给视图技术(Thymeleaf),并且我有一个控制器方法,它接受带有填写的表单的POST请求。代码
public class Product{
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Product() {}
public Product(String name) {
this.name = name;
}
}
这是我的表单支持课程:
public class ListForm {
private Map<Category, List<Product>> list;
public ListForm() {
list = new HashMap<>();
}
public void setList(Map<Category, List<Product>> list) {
this.list = list;
}
public Map<Category, List<Product>> getList() {
return this.list;
}
}
我的控制器:
@ModelAttribute("fullList")
public ListForm fullList() {
// populate the ListForm with values
{
@RequestMapping("/")
public String home(@ModelAttribute("fullList") ListForm fullList) {
return "index";
}
@PostMapping("/update")
public String update(@ModelAttribute ListForm form) {
// process the submitted form
return "index";
}
这是 Thymeleaf 模板:
<body>
<form th:object="${fullList}" method="post" th:action="@{/update}">
<article th:each="category : *{list}">
<div th:each="item,itemStat : ${category.value}">
<input type="text" th:field="*{list[__${category.key}__][__${itemStat.index}__].name}">
</div>
</article>
<input type="submit">
</form>
</body>
问题
Request processing failed: org.springframework.beans.NullValueInNestedPathException: Invalid property 'list[FRUITS][0]' of bean class [spring.mvc.ListForm]: Cannot access indexed value of property referenced in indexed property path 'list[FRUITS][0]': returned null
地图条目中的空列表似乎导致了问题。 Spring MVC 不会自动创建新的 Product
并将其添加到列表中。研究
Map<Category, List<Product>>
切换到
Map<Categroy, List<String>>
(并进行所需的调整),那么它就可以正常工作 - Spring MVC 确实创建了一个新的字符串。另外,如果我将控制器 POST 方法更改为这样:
@PostMapping("/update")
public String update(@ModelAttribute("fullList") ListForm form) {
// process the submitted form
return "index";
}
它有效,因为 @ModelAttribute 引用了由 @ModelAttribute
方法创建的 ListForm。但这不是我需要的 - 我需要用户填写的表格。我该如何解决这个问题?我需要注册一个自定义的 DataBinder 或类似的东西吗?