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

Spring MVC项目JSP遍历Comments列表报NumberFormatException如何解决

问题修复方案

错误根本原因

JSP中<c:forEach>标签的var属性值和items属性对应的Model变量名重名,导致EL表达式解析异常。当var设为commentsList时,会覆盖Model中原有的列表变量commentsList,EL解析${commentsList.comment}时,误将当前作用域中的commentsList识别为列表类型,尝试把字符串comment转为整数下标来获取列表元素,因此抛出NumberFormatException。你之前仅传递单个元素时没有触发遍历逻辑,不会出现变量覆盖,所以运行正常。

具体修改步骤

1. 修改JSP遍历代码

调整<c:forEach>的var变量名,使其和列表变量名不重复,修改后代码如下:

<div>
    <form class="form-horizontal" action="do_comment" method="POST">
        <textarea rows="2" class="comment-area"></textarea>
        <input type="submit" value="Comment"/>
    </form>
    <c:forEach items="${commentsList}" var="commentItem">
    <div>
        <p>${commentItem.comment}</p><hr><br>
        </div>
    </c:forEach>
</div>

2. 恢复Controller层逻辑

换回最初传递完整评论列表的代码即可,无需仅传递单个元素:

@RequestMapping("post/{id}")
public ModelAndView post(ModelAndView model, @PathVariable Integer id) throws IOException {
    List<Posts> post = postDao.findPostById(id);
    List<Comments> comments = (List<Comments>) commentsRepository.findAll();
    model.addObject("post", post.get(0));
    model.addObject("commentsList",comments);
    model.setViewName("Post");
    return model;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 10:27:04