我试图将包含对象的ArrayList从servlet传递到JSP。但
Servlet文件:
request.setAttribute("servletName", categoryList); //categorylist is an arraylist contains object of class category getServletConfig().getServletContext().getRequestDispatcher("/GetCategory.jsp").forward(request,response);
JSP文件:
//category class <% Category category = new Category(); //creating arraylist object of type category class ArrayList<Category> list = ArrayList<Category>(); //storing passed value from jsp list = request.getAttribute("servletName"); for(int i = 0; i < list.size(); i++) { category = list.get(i); out.println( category.getId()); out.println(category.getName()); out.println(category.getMainCategoryId() ); } %>
在servlet代码中,使用指令request.setAttribute("servletName", categoryList)将您的列表保存在请求对象中,并使用名称“ servletName”进行引用。 顺便说一句,使用然后使用名称“ servletName”作为列表是很令人困惑的,也许最好将其命名为“列表”或类似名称: request.setAttribute("list", categoryList) 无论如何,假设您不更改您的Serlvet代码,并使用名称“ servletName”存储列表”。当您到达JSP时,有必要从请求中检索列表,为此,您只需要request.getAttribute(...)方法。
request.setAttribute("servletName", categoryList)
request.setAttribute("list", categoryList)
request.getAttribute(...)
<% // retrieve your list from the request, with casting ArrayList<Category> list = (ArrayList<Category>) request.getAttribute("servletName"); // print the information about every category of the list for(Category category : list) { out.println(category.getId()); out.println(category.getName()); out.println(category.getMainCategoryId()); } %>