最好使用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答案。