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 :)
You can use JSTL's foreach.
You need also to import JSTL core:
There are multiple ways this can be done (with some changes in your scheme)
Using JSTL:
Create a bean with two fields as
food
andfood_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:If you are using struts:
Here
list
is object key which will be used to retrieve the list from context (page/session)It would be better to use a
java.util.Map
to store the key and values instead of twoArrayList
, like:Now to iterate the map in the JSP use:
Or without 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.
This will solve your problem.
You can retrieve the list in JSP as