一尘不染

在JSP中迭代ArrayList

jsp

我的班级中有两个arraylist,我想将其发送到JSP,然后在select标记中迭代arraylist中的元素。

这是我的课:

package accessData;

import java.util.ArrayList;

public class ConnectingDatabase 
{
   ArrayList<String> food=new ArrayList<String>();
   food.add("mango");
   food.add("apple");
   food.add("grapes");

   ArrayList<String> food_Code=new ArrayList<String>();
   food.add("man");
   food.add("app");
   food.add("gra");
}

我想在JSP中将food_Code迭代为select标记中的选项,将food作为值作为JSP中Select标记中的值。我的JSP是:

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

// Don't know how to iterate

</select>

任何代码段均受到高度赞赏。提前致谢 :)


阅读 389

收藏
2020-06-08

共1个答案

一尘不染

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

2020-06-08