在JSP中迭代ArrayList
我的课程中有两个arraylists,我想将它发送到我的JSP,然后在select标签中迭代arraylist中的元素。
这是我的class级:
package accessData; import java.util.ArrayList; public class ConnectingDatabase { ArrayList food=new ArrayList(); food.add("mango"); food.add("apple"); food.add("grapes"); ArrayList food_Code=new ArrayList(); food.add("man"); food.add("app"); food.add("gra"); }
我想将food_Code作为select标签中的选项和food作为JSP中Select元件中的值进行迭代; 我的JSP是:
// Don't know how to iterate
任何一段代码都非常受欢迎。 提前致谢 :)
最好使用java.util.Map
来存储键和值,而不是两个ArrayList
,如:
Map foods = new HashMap(); // 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
现在在JSP中迭代地图使用:
或者没有JSTL:
要了解有关使用JSTL进行迭代的更多信息,这是一个很好的答案 ,这是一个关于如何一般使用JSTL的好教程 。
${foodItem.propertyOfBean}
这将解决您的问题。
你可以使用JSTL的foreach。
${item}
您还需要导入JSTL核心:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
有多种方法可以完成(在您的方案中进行一些更改)
使用JSTL:
-
创建一个包含两个字段作为
food
和food_code
公共类食品{私人食品; private String food_code; // Setter / getters跟随}
现在页面上可用的arraylist将列出Food
对象。 在JSP代码中,您可以使用以下内容:
如果你使用struts:
这里的list
是对象键,它将用于从上下文(页面/会话)中检索列表
您可以在JSP中检索列表