您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

在JSP中迭代ArrayList

在JSP中迭代ArrayList

最好使用a java.util.Map来存储键和值,而不是两个ArrayList,例如:

Map<String, String> foods = new HashMap<String, String>();

// here key stores the food codes
// and values are that which will be visible to the user in the drop-down
foods.put("man", "mango");
foods.put("app", "apple");
foods.put("gra", "grapes");

// if this is your servlet or action class having access to HttpRequest object then
httpRequest.setAttribute("foods", foods); // so that you can retrieve in JSP

现在要在JSP中迭代地图,请使用:

<select id="food" name="fooditems">
    <c:forEach items="${foods}" var="food">
        <option value="${food.key}">
            ${food.value}
        </option>
    </c:forEach>
</select>

或不带JSTL:

<select id="food" name="fooditems">

<%
Map<String, String> foods = (Map<String, String>) request.getAttribute("foods");

for(Entry<String, String> food : foods.entrySet()) {
%>

    <option value="<%=food.getKey()%>">
        <%=food.getValue() %>
    </option>

<%
}
%>

</select>

要了解有关使用JSTL进行迭代的更多信息 ,这里是一个很好的SO答案。

其他 2022/1/1 18:15:47 有541人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶