如何分配数组列表来选择jsp中的选项 [英] how to assign arraylist to select option in jsp
问题描述
我有这个列表:
ArrayList list = new ArrayList();
我写下这个清单选择选项:
< TD>
< select name =database1>
< option value =selected> select< / option>
<%
for(int i = 0; i< list.size(); i ++){
Field = list.get(i).toString();
%>
< / option><%value =><%=字段%>><%=字段%>
<%}%>
< / select>
< / td>
所以我的要求是不使用for循环。我们直接在选择选项
中写入 list
。
不推荐在jsp中使用java代码。你应该尽量避免它。
在你的情况下需要遵循的方法是首先将Arraylist设置为调用jsp页面的servlet中的一个属性。
Servlet代码
ArrayList databaseArrayList = new ArrayList() ;
...
request.setAttribute(databaseList,databaseArrayList);
然后,在JSP代码中,使用jstl遍历列表的值以填充选择
$ b JSP代码 < select name =database1>
< c:forEach items =$ {databaseList}var =databaseValue>
< option value =$ {databaseValue}>
$ {databaseValue}
< / option>
< / c:forEach>
< / select>
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
.
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?
这篇关于如何分配数组列表来选择jsp中的选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!