how to assign arraylist to select option in jsp

2020-05-29 02:38发布

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.

标签: html jsp
2条回答
何必那么认真
2楼-- · 2020-05-29 02:42

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

查看更多
一夜七次
3楼-- · 2020-05-29 03:07

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>

Read this: How to avoid Java code in JSP files?

查看更多
登录 后发表回答