Html 如何分配arraylist以在jsp中选择选项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19293792/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 14:19:08  来源:igfitidea点击:

how to assign arraylist to select option in jsp

htmljsp

提问by suresh manda

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 listin select option.

所以我的要求是不使用 for 循环。我们直接写list进去select option

回答by Sorter

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

不建议在jsp中使用java代码。你应该尽量避免它。

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.

在您的情况下需要遵循的方法是首先将 Arraylist 设置为调用 jsp 页面的 servlet 中的一个属性。

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 代码中,使用 jstl 遍历列表的值以填充选择选项。

JSP Code

JSP代码

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

阅读:如何避免 JSP 文件中的 Java 代码?

回答by Skms

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

我猜您做得很好,只需更改您的代码,例如:- <option value="<%out.print(Field); %>"></option>希望这有效