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

JSP/JSTL中forEach的var作为List.get()参数失效问题咨询

问题原因与解决方案

核心原因

你用<c:forEach>定义的var="i"是字符串类型,而List.get()方法需要的是int类型的索引参数。EL表达式不会自动将字符串转为整数,导致方法调用参数不匹配,无法获取对应元素。

另外你尝试的<%=List.get(i).getName()%>无效,是因为JSTL的变量(存在pageContext作用域)和脚本(Scriptlet)的变量不在同一个作用域,脚本里根本找不到i这个变量。

正确写法

方式1:直接遍历List元素(推荐,更简洁)

不需要手动处理索引,用<c:forEach>的items属性直接遍历List中的对象:

<c:forEach var="item" items="${List}">
  <option value="2" selected>
    ${item.name}
  </option>
</c:forEach>

这里${item.name}是EL的属性访问语法,会自动调用对象的getName()方法,比直接写get()更简洁。

方式2:需要索引时用varStatus

如果确实需要用到索引值,用<c:forEach>的varStatus属性,它的index属性是int类型,能直接作为get()的参数:

<c:forEach varStatus="status" begin="0" end="${List.size() - 1}">
  <option value="2" selected>
    ${List.get(status.index).name}
  </option>
</c:forEach>

注意:原来的end="${List.size()}"会导致索引越界,因为List的索引从0开始,最后一个元素的索引是size()-1,所以要把end设为${List.size()-1}。

内容的提问来源于stack exchange,提问作者Raúl Peñate

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 13:06:17