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

Spring Boot访问@PostMapping路径报500 TemplateProcessingException异常求解

错误根本原因

你遇到的报错核心是Thymeleaf渲染表单阶段无法找到绑定对象:

  • 你的greeting.html里表单通过th:object="${greeting}"绑定了名为greeting的模型对象,同时用th:field做了表单字段和对象属性的绑定
  • 原来的@GetMapping("/greeting")方法仅向Model中添加了name属性,没有添加greeting对象,Thymeleaf渲染模板时找不到对应的绑定对象,直接抛出没有找到bean名称为'greeting'的BindingResult或普通目标对象作为请求属性可用异常。

修复方案的底层原理

你在GET方法参数中添加Greeting greeting后问题解决,本质是触发了Spring MVC的模型参数自动绑定规则:
当控制器方法的参数是没有添加@RequestParam、@PathVariable等特殊注解的普通JavaBean类型时,Spring MVC会自动执行两个操作:

  1. 调用该类的无参构造方法实例化对象
  2. 按照「类名首字母小写」的规则,自动将实例化后的对象添加到Model中,也就是你当前场景里,Spring自动帮你执行了model.addAttribute("greeting", new Greeting())的操作
    刚好和你模板里th:object="${greeting}"要求的对象名匹配,Thymeleaf渲染时就能拿到合法的绑定对象,不会再报错。

等价的其他修复方式

你当前的写法和手动往Model里放Greeting对象效果完全一致,比如下面的写法也可以解决问题:

@GetMapping("/greeting")
public String greeting(@RequestParam(name="name", required=false, defaultValue="World") String name, Model model) {
    model.addAttribute("name", name);
    model.addAttribute("greeting", new Greeting()); // 手动添加绑定对象
    return "greeting.html";
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 22:24:02