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

提交评论触发org.springframework.core.convert.ConversionFailedException报错原因是什么?

错误根因

这个报错是参数绑定命名冲突导致的,核心原因有两个:

  1. 你CommentController中addPage方法的@ModelAttribute参数名为comment,刚好和表单提交的评论内容字段的请求参数名comment完全一致。Spring MVC会优先尝试将请求中名为comment的字符串值(就是你输入的GoodNight)直接转换为Comment实体类型,转换过程中尝试把字符串转成Long类型的主键id,因此触发类型转换失败。
  2. 页面comment.html中遍历评论列表的迭代变量也命名为comment,和实体类字段、参数名重复,进一步加剧了参数绑定的逻辑混乱。

解决方案

按以下步骤修改即可解决:

  1. 修改Controller中addPage方法的参数名,避免和请求参数名冲突:
@PostMapping("/addComment")
// 给@ModelAttribute指定名称,参数名改为不和字段冲突的名字
public String addPage(@ModelAttribute("newComment") Comment newComment, Model model) {
    System.out.println(newComment.getComment());
    commentRepository.save(newComment);
    return "test";
}
  1. 修改comment.html中遍历评论的代码,删除无用的th:object,修改迭代变量名:
<!-- 去掉多余的th:object,迭代变量名改为item避免冲突 -->
<div th:each="item:${commentList}">
    <div>No.[[${item.id}]] : [[${item.comment}]]</div>
</div>
  1. (可选优化)新增评论时主键id是自增生成的,不需要表单传递,直接删除表单中id的隐藏域即可:
<form th:action="@{/addComment}" th:object=${Comment} method="post">
    <!-- 删除这行:<input type="hidden" th:field="*{id}"> -->
    <label for="comment">comment:</label> 
    <input type="text"  th:field="*{comment}">
    <input type="hidden" th:field="*{user_id}" th:value="${user.getUser_id()}"> 
    <button>add</button>
</form>

修改完成后重新启动项目测试即可正常提交评论。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 04:06:02