将 ArrayList 从 servlet 传递到 JSP [英] Passing ArrayList from servlet to JSP
问题描述
我试图将包含对象的 ArrayList 从 servlet 传递到 JSP.但是
I am trying to pass ArrayList which contains object from servlet to JSP. But
Servlet 文件:
Servlet file:
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"来引用它.
顺便说一句,使用 then 名称servletName"作为列表是相当混乱的,也许最好称它为list"或类似的东西:request.setAttribute("list", categoryList)
无论如何,假设您不更改 serlvet 代码,并使用名称servletName"存储列表.当您到达 JSP 时,有必要从请求中检索列表,为此您只需要 request.getAttribute(...)
方法.
In the servlet code, with the instruction request.setAttribute("servletName", categoryList)
, you save your list in the request object, and use the name "servletName" for refering it.
By the way, using then name "servletName" for a list is quite confusing, maybe it's better call it "list" or something similar: request.setAttribute("list", categoryList)
Anyway, suppose you don't change your serlvet code, and store the list using the name "servletName". When you arrive to your JSP, it's necessary to retrieve the list from the request, and for that you just need the request.getAttribute(...)
method.
<%
// 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());
}
%>
这篇关于将 ArrayList 从 servlet 传递到 JSP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!