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

Spring MVC中如何通过JSTL遍历列表匹配条件并设置选中选项

我来帮你搞定这个下拉框默认选中的问题!你已经搭好了基础的JSTL结构,只需要完善判断逻辑,把选中的资产和遍历的资产做匹配,给对应的<option>加上selected属性就行。

完整实现代码

这里我补全并优化了你的代码,核心是通过JSTL判断当前遍历的资产是否和控制器传递的asset匹配:

<table>
  <tr>
    <td>Asset Id :</td>
    <td>
      <form id="getAssetForm" method="get">
        <select id="assetid" name="assetid" onchange="submitForm(this);">
          <!-- 遍历全部资产列表 -->
          <c:if test="${not empty assets}">
            <c:forEach items="${assets}" var="assetItem">
              <!-- 用choose判断是否为选中资产 -->
              <c:choose>
                <c:when test="${not empty asset and asset.id eq assetItem.id}">
                  <option value="${assetItem.id}" selected>${assetItem.id}</option>
                </c:when>
                <c:otherwise>
                  <option value="${assetItem.id}">${assetItem.id}</option>
                </c:otherwise>
              </c:choose>
            </c:forEach>
          </c:if>
          <!-- 处理资产列表为空的情况 -->
          <c:if test="${empty assets}">
            <option value="" disabled>No assets available</option>
          </c:if>
        </select>
      </form>
    </td>
  </tr>
</table>

关键细节说明

  1. 匹配逻辑:核心判断${not empty asset and asset.id eq assetItem.id},先确保asset不为空(避免空指针),再对比资产的唯一标识(这里用id,你可以换成实际业务里的属性,比如assetCode)。
  2. 简化写法:如果觉得<c:choose>太繁琐,也可以用EL三元表达式直接写在<option>里,代码更简洁:
<option value="${assetItem.id}" ${not empty asset and asset.id eq assetItem.id ? 'selected' : ''}>
  ${assetItem.id}
</option>
  1. 边界处理:加了资产列表为空的提示选项,提升页面的友好性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 07:40:44