4

I have the list:

ArrayList list = new ArrayList();

I write this list select option:

<td>
    <select name="database1">
        <option value="" selected>select</option>
        <%
        for(int i=0;i<list.size();i++) {
            Field=list.get(i).toString();
        %>
        <option value="<%=Field %>"><%=Field %></option>
        <%} %>
    </select>
</td>

So my requirement is without using for loop. We directly write list in select option.

2 Answers 2

9

It's not recommended to use java code inside jsp. You should try to avoid it.

The approach that needs to be followed in your case, is to first set the Arraylist as an attribute in the servlet that is calling the jsp page.

Servlet Code

ArrayList databaseArrayList = new ArrayList();
...
request.setAttribute("databaseList", databaseArrayList);     

Then, in the JSP code, use jstl to iterate through the values of the list to populate the select options.

JSP Code

<select name="database1">
  <c:forEach items="${databaseList}" var="databaseValue">
    <option value="${databaseValue}">
        ${databaseValue}
    </option>
  </c:forEach>
</select>

I've written an article for looping over HashMap and ArrayList in JSP

Sign up to request clarification or add additional context in comments.

5 Comments

donot use any loop.how to write list to option directly
You can directly write the values in the options. If values are few. list.get(i) way of doing it is not advisable, if the list is large or going to grow or shrink in future.
this is ok na<td><select name="database1"> <option value="list.get(i)">list.get(i)</option> </select> </td>
This will work. But If you are not using the for loop, you have to type all the indexes into list.get(). If you are using the loop to print list.get(i), why not go with the jstl for-each loop. It will make your code more readable.
need to fix </c:forEach>
1

I guess You are doing great, just change your code like:- <option value="<%out.print(Field); %>"></option> Hope this works

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.