Ani*_*rma 9 java jsp arraylist
我的课程中有两个arraylists,我想将它发送到我的JSP,然后在select标签中迭代arraylist中的元素.
这是我的班级:
package accessData;
import java.util.ArrayList;
public class ConnectingDatabase
{
ArrayList<String> food=new ArrayList<String>();
food.add("mango");
food.add("apple");
food.add("grapes");
ArrayList<String> food_Code=new ArrayList<String>();
food.add("man");
food.add("app");
food.add("gra");
}
Run Code Online (Sandbox Code Playgroud)
我想将food_Code作为select标签中的选项和food作为JSP中Select元件中的值进行迭代; 我的JSP是:
<select id="food" name="fooditems">
// Don't know how to iterate
</select>
Run Code Online (Sandbox Code Playgroud)
任何一段代码都非常受欢迎.提前致谢 :)
Pra*_*h K 15
最好使用a java.util.Map
来存储键和值而不是两个ArrayList
,例如:
Map<String, String> foods = new HashMap<String, String>();
// here key stores the food codes
// and values are that which will be visible to the user in the drop-down
foods.put("man", "mango");
foods.put("app", "apple");
foods.put("gra", "grapes");
// if this is your servlet or action class having access to HttpRequest object then
httpRequest.setAttribute("foods", foods); // so that you can retrieve in JSP
Run Code Online (Sandbox Code Playgroud)
现在在JSP中迭代地图使用:
<select id="food" name="fooditems">
<c:forEach items="${foods}" var="food">
<option value="${food.key}">
${food.value}
</option>
</c:forEach>
</select>
Run Code Online (Sandbox Code Playgroud)
或者没有JSTL:
<select id="food" name="fooditems">
<%
Map<String, String> foods = (Map<String, String>) request.getAttribute("foods");
for(Entry<String, String> food : foods.entrySet()) {
%>
<option value="<%=food.getKey()%>">
<%=food.getValue() %>
</option>
<%
}
%>
</select>
Run Code Online (Sandbox Code Playgroud)
要了解有关使用JSTL进行迭代的更多信息,这是一个很好的答案,这是一个关于如何一般使用JSTL 的好教程.