Reputation: 353
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%=new Date() %>
<%
ArrayList al = new ArrayList();
al.add("C");
al.add("A");
al.add("E");
al.add("B");
al.add("D");
al.add("F");
%>
<select>
<option value="<%=al%>"></option>
</select>
</body>
</html>
This is my code i want to add Arraylist in drop down in Jsp I dont know how to Bind arraylist in html obtion or drop down please help me i have tried Much but unable to do this .
Upvotes: 8
Views: 69777
Reputation: 11
Try this: declare your arraylist in between <%! … %>
<%! ArrayList al = new ArrayList(); %>
Upvotes: 1
Reputation: 49372
You have to use JSTL <forEach>
to iterate through the elements and add it to the select-option
. Probably make the List
a scoped attribute . Populate the List
object in the servlet, set it in request/session
scope and forward the request
to this JSP. Remember you can populate the List
in the JSP itself and use pageScope
to refer it , but that will be bad design in my opinion.
<select>
<c:forEach var="element" items="${al}">
<option value="${element}">${element}</option>
</c:forEach>
</select>
Here , al
is the name of the attribute which stores the List
in probably request
or session
scope.
Use JSTL in project :
Download the JSTL 1.2 jar .
Declare the taglib in JSP file for the JSTL core taglib.
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
If you want to use just the scriptlets(which is bad off course) :
<%
List<String> al = new ArrayList<String>();
al.add("C");
..........
...........
%>
<select>
<% for(String element: al) { %>
<option value="<%=element%>"><%=element%></option>
<% } %>
</select>
The above code will work if you have defined the List
as List<String>
, or else you need to cast the element to String
.
Read How to avoid Java Code in JSP-Files?.
Upvotes: 12
Reputation: 1662
Take a look at the tag in the core JSTL library.
Store the arraylist in pageScope.myList and loop as follows:
<select>
<c:forEach items="${pageScope.myList}" var="item" varStatus="status">
<option value='${item}'></option>
</c:forEach >
</select>
This is preferable than using scriptlets which are not considered good practice
Upvotes: 1
Reputation: 17422
EDITED
Try this:
<%
ArrayList al = new ArrayList();
al.add("C");
al.add("A");
al.add("E");
al.add("B");
al.add("D");
al.add("F");
%>
<select>
<% for(int i = 0; i < al.size(); i++) {
String option = (String)al.get(i);
%>
<option value="<%= option %>"><%= option %></option>
<% } %>
</select>
</body>
</html>
Upvotes: 6