Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to add arraylist in Jsp

Tags:

java

jsp

<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 .

like image 841
Aman Kumar Avatar asked Jul 26 '13 10:07

Aman Kumar


1 Answers

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 :

  1. Download the JSTL 1.2 jar .

  2. 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?.

like image 82
AllTooSir Avatar answered Oct 21 '22 04:10

AllTooSir