Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 214
Anish Sharma Avatar asked May 06 '13 10:05

Anish Sharma


People also ask

How can I get getAttribute in JSP?

1) First create data at the server side and pass it to a JSP. Here a list of student objects in a servlet will be created and pass it to a JSP using setAttribute(). 2) Next, the JSP will retrieve the sent data using getAttribute(). 3) Finally, the JSP will display the data retrieved, in a tabular form.

Which tag is used to iterate over a list of items in JSP?

JSTL foreach tag allows you to iterate or loop Array List, HashSet or any other collection without using Java code. After the introduction of JSTL and expression language(EL) it is possible to write dynamic JSP code without using scriptlet which clutters jsp pages.


1 Answers

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.

like image 151
Prakash K Avatar answered Sep 27 '22 18:09

Prakash K