You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring MVC绑定Map<Category, List<Product>>表单提交报错求助

Spring MVC嵌套Map+List表单提交时的NullValueInNestedPathException问题

问题背景

我开发了一个购物清单页面,按分类展示产品列表,允许用户指定每个产品的数量,提交按钮将表单数据提交至后端。页面需要按分类展示产品,因此我通过Thymeleaf向视图传递了一个Map<Category, List<Product>>对象,并编写了处理POST请求的控制器方法。

相关代码

模型类Product

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;
    }
    
}

表单支持类ListForm

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() {
       // 填充ListForm数据
    }

    @RequestMapping("/")
    public String home(@ModelAttribute("fullList") ListForm fullList) {
        return "index";
    }

    @PostMapping("/update")
    public String update(@ModelAttribute ListForm 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

问题出在Map对应条目为空列表时,Spring MVC无法自动创建新的Product对象并添加到列表中。

已尝试的方案

  • 将列表类型改为Map<Category, List<String>>(并做对应调整)后,功能可正常工作,Spring MVC会自动创建新的String对象;
  • 修改POST方法的@ModelAttribute指定为"fullList"也能正常工作,但这不符合需求,我需要获取用户填写的表单数据。

求助

请问该如何解决此问题?是否需要注册自定义DataBinder?

内容的提问来源于stack exchange,提问作者YoavKlein

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 21:53:28