在 Spring MVC 中绑定地图<String, List<MyType>>

问题描述 投票:0回答:1
搭建舞台

我有一个购物清单页面,它显示按类别分组的产品列表,并允许用户指定每个产品的数量。有一个提交按钮可以将表单提交到后端。页面上的商品需要按照类别展示。

因此,我将一个

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 或类似的东西吗?

java spring spring-mvc
1个回答
0
投票
你可以通过这个。 。 。 。

https://medium.com/@ganeshbn21/bind-a-map-string-list-mytype-in-spring-mvc-0bc133bf630f

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.