10

我的班级中有两个数组列表,我想将它发送到我的 JSP,然后在选择标记中迭代数组列表中的元素。

这是我的课:

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");
}

我想迭代 food_Code 作为选择标签中的选项和食物作为 JSP 中选择标签中的值;我的 JSP 是:

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

// Don't know how to iterate

</select>

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

4

5 回答 5

17

最好使用 ajava.util.Map来存储键和值而不是 two 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 进行迭代的信息,这里是一个很好的答案,这里是一个关于如何使用 JSTL的很好的教程。

于 2013-05-06T11:14:06.030 回答
4
<c:forEach items="${list}" var="foodItem">
 ${foodItem.propertyOfBean}
</c:forEach>

This will solve your problem.

于 2013-05-06T10:56:41.673 回答
4

您可以使用 JSTL 的 foreach。

<c:forEach items="${foodItems}" var="item">
   ${item}
</c:forEach>

您还需要导入 JSTL 核心:

<%@ taglib prefix="c" 
       uri="http://java.sun.com/jsp/jstl/core" %>
于 2013-05-06T10:55:14.817 回答
1

You can retrieve the list in JSP as

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

  <c:forEach items="${listname}" var="food" >

     <option value="${food}"> ${food} </option>

  </c:forEach>

</select>
于 2013-05-06T11:09:11.690 回答
0

There are multiple ways this can be done (with some changes in your scheme)

Using JSTL:

  1. Create a bean with two fields as food and food_code

    public class Food{ private String food; private String food_code; // Setter/getters follows }

Now the arraylist available on the page will be list Food objects. In the JSP code, you can use following:

<select name="fooditems">
    <c:forEach items="${list}" var="item">
        <option value="${item.food_code}">${item.food}</option>
    </c:forEach>
</select>

If you are using struts:

<html:select property="fooditems" >
<html:optionsCollection property="list" label="food" value="food_code" />
</html:select>

Here list is object key which will be used to retrieve the list from context (page/session)

于 2013-05-06T11:08:59.777 回答