How to add arraylist to 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 to the Jsp folder. I don't know how to link arraylist in html obtion or go down, please help me. I tried a lot, but could not do it.
edited
Try the following:
<% 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> You must use the JSTL <forEach> to iterate over the elements and add them to the select-option . Probably make List a attribute with scope. Fill the List object in the servlet, set it to the request/session and move the request to this JSP. Remember that you can populate the List in the JSP itself and use pageScope to reference it, but that will be a 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 in which the List scope is stored, possibly request or session .
Use JSTL in the project:
Download the JSTL 1.2 jar.
Declare taglib in the JSP file for the JTL core taglib .
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
If you want to use only scriptlets (which is bad from the 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 defined List as List<String> , otherwise you need to pass the element to String .
Take a look at the tag in the JSTL core library.
Save arraylist in pageScope.myList and follow these steps:
<select> <c:forEach items="${pageScope.myList}" var="item" varStatus="status"> <option value='${item}'></option> </c:forEach > </select> This is preferable to using scripts that are not considered good practice.