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

SpringBoot中Thymeleaf表单报'product' bean无请求属性错误如何解决

错误原因

你遇到的Neither BindingResult nor plain target object for bean name 'product' available as request attribute错误是Thymeleaf表单绑定时找不到对应名称的Model属性导致的,具体原因如下:

  • Spring MVC默认会将Controller方法参数中的实体类对象自动加入Model,属性名默认规则为类名首字母小写。你的实体类为Products,所以自动加入Model的属性名为products。
  • 你原有的HTML表单中th:object="${product}"指定绑定的属性名为product,和默认的products名称不匹配,同时你没有手动将product对象加入Model,导致Thymeleaf渲染页面时找不到对应的绑定对象,直接抛出错误。
  • 你将HTML和请求中的bean名改为products后可以正常运行,就是因为和Spring MVC默认生成的属性名匹配上了。
解决方法

有两种常用解决方案,可根据需求选择:

方案1:保留表单语义,使用product作为绑定名

单个产品对象用product命名更符合语义,只需手动指定Model属性名即可:

步骤1:给Controller的实体参数加@ModelAttribute注解

在GET和POST请求的Products参数前添加@ModelAttribute("product")注解,指定Spring MVC自动将该对象以product为key加入Model:

@GetMapping("/add")
public String add(@ModelAttribute("product") Products product, Model model) {
    List<Category> categories = categoryRepo.findAll();
    model.addAttribute("categories", categories);
    return "admin/products/add";
}

@PostMapping("/add")
public String add(@Valid @ModelAttribute("product") Products product, BindingResult bindingResult, 
                    MultipartFile file, RedirectAttributes redirectAttributes, 
                    Model model) throws IOException {
    List<Category> categories = categoryRepo.findAll();
    if (bindingResult.hasErrors()) {
        model.addAttribute("categories", categories);
        return "admin/products/add";
    }
    // 后续原有代码保持不变
}

步骤2:保持HTML代码不变

不需要修改原有HTML中th:object="${product}"的配置,直接运行即可。

方案2:沿用现有修改,无需调整Controller

直接将HTML中表单的th:object="${product}"改为th:object="${products}",表单内部的th:field="*{xxx}"属性不需要修改,即可和Spring MVC默认生成的Model属性名匹配,正常运行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 12:51:01