在JSP中的ArrayList迭代 [英] Iterate ArrayList in JSP

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

问题描述

我在我的类中的两个的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");
}

我要遍历food_ code作为选择标记和食物在JSP标签中选择选项的值;我的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>

任何一件code是高度AP preciated。在此先感谢:)

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:

Or without 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迭代这里是一个很好的<一个href=\"http://stackoverflow.com/questions/2117557/how-to-iterate-an-arraylist-inside-a-hashmap-using-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迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆