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

Spring MVC JSP渲染下拉框报NumberFormatException: For input string: "id"错误求解

问题根因分析
  • 核心错误是Spring form标签库解析<form:option>属性时,错误将字面量字符串"id"当做绑定对象的属性值尝试类型转换,你的写法没有正确取出Documenttypes实体的id属性值,反而把属性名字符串"id"直接传到了需要数字类型的value属性中,触发数字格式转换异常。
  • 常见的错误写法场景:
    1. 写<form:option value="id" label="name"/>,没有加EL表达式${},直接把属性名写死成了字符串
    2. EL表达式写错,比如错误调用集合本身的id属性${documenttypesList.id},而不是调用遍历出来的单个元素的属性
    3. Documenttypes实体类的id字段没有提供public的getter方法,EL表达式取不到值,直接把属性名当做值输出了
解决方法

按照下面的步骤排查修改即可:

  1. 首先确认控制器逻辑正确,参考示例:
@GetMapping("/addDocument")
public String addDocument(Model model) {
    // 存入表单绑定的空Documents对象
    model.addAttribute("document", new Documents());
    // 查询所有文档类型存入Model
    List<Documenttypes> documenttypesList = documenttypesRepository.findAll();
    model.addAttribute("documenttypesList", documenttypesList);
    return "add-document";
}
  1. 修正JSP中下拉框的写法,必须用EL表达式取出遍历的单个元素的属性值,参考示例:
<%-- 首先引入必要的标签库 --%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<%-- form标签绑定model中的document对象 --%>
<form:form modelAttribute="document" method="post" action="/saveDocument">
    <%-- 下拉框绑定document的typeid字段 --%>
    <form:select path="typeid">
        <%-- 遍历documenttypesList,每次循环的单个元素存到type变量 --%>
        <c:forEach items="${documenttypesList}" var="type">
            <%-- 用EL表达式取type的id作为value,取type的名称作为显示文本 --%>
            <form:option value="${type.id}" label="${type.typename}"/>
        </c:forEach>
    </form:select>
    <input type="submit" value="提交"/>
</form:form>
  1. 确认Documenttypes实体类中id和类型名称字段都有public的getter方法,EL表达式才能正常读取属性值:
public class Documenttypes {
    private Integer id;
    private String typename;
    // 必须提供public getter
    public Integer getId() { return id; }
    public String getTypename() { return typename; }
    // 其他setter、构造方法省略
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 05:15:03