Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
194 views
in Technique[技术] by (71.8m points)

java - Iterate ArrayList in 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.

Here is my class:

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

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 :)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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>

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>

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...