Search code examples
javajspjstl

JSP use contents of an array list in a drop down box


I have an arraylist that is declared and populated in a JSP file:

<% for(int i=0; i< GDI.getRow(); i++){
    associatedLines[i] = GDI.getRow().get(i).getNumplanindex;
}

ArrayList<Integer> availableLines = new ArrayList<Integer>();
for(int i=0; i<associatedLines.length; i++){
    if(associatedLines[i] == null){
         availableLines.add(i);
    }
}

%>

I would like to use the contents of availableLines in the dropdown list and be able to store the value selected to be used somewhere else.

I am almost certain that I need to use JSTL but I am not sure how to do it.

Hopefully somebody can help. Thanks!


Solution

  • You can add the bellow line just after the for loop in your scriptlet:

    request.setAttribute("availableLines", availableLines);
    

    And then you can use the availableLines variable in your drop down list using JSTL like bellow:

     <select>
        <c:forEach var="line" items="${availableLines}">
            <option><c:out value="${line}"/></option>
        </c:forEach>
     </select>
    

    I think, this answers your original question.

    Edit:

    But one thing you should know that, writing scriptlet is deprecated for years! So it is advised to move your scriptlet code to your corresponding servlet. Here is a step by step tutorial for Servlet and jsp for beginners.