本文介绍了在 JSP 中迭代 ArrayList的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

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

I have two arraylists in my class and I want to send it to my JSP and then iterate the elements in arraylist in a select tag.

这是我的课:

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 迭代为 Select 标签中的值;我的 JSP 是:

I want to iterate food_Code as options in select tag and food as values in Select tag in JSP; my JSP is:

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

// Don't know how to iterate

</select>

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

Any piece of code is highly appreciated. Thanks in Advance :)

推荐答案

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

It would be better to use a java.util.Map to store the key and values instead of two ArrayList, like:

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 中迭代地图使用:

Now to iterate the map in the JSP use:

<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 答案,这里有一个关于如何使用 JSTL 的很好的教程总的来说.

To know more about iterating with JSTL here is a good SO answer and here is a good tutorial about how to use JSTL in general.

这篇关于在 JSP 中迭代 ArrayList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-07 01:51