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>
关键细节说明
- 匹配逻辑:核心判断
${not empty asset and asset.id eq assetItem.id},先确保asset不为空(避免空指针),再对比资产的唯一标识(这里用id,你可以换成实际业务里的属性,比如assetCode)。 - 简化写法:如果觉得
<c:choose>太繁琐,也可以用EL三元表达式直接写在<option>里,代码更简洁:
<option value="${assetItem.id}" ${not empty asset and asset.id eq assetItem.id ? 'selected' : ''}> ${assetItem.id} </option>
- 边界处理:加了资产列表为空的提示选项,提升页面的友好性。
内容的提问来源于stack exchange,提问作者Developer Desk
相关产品推荐
相关产品推荐

