Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am trying to pass ArrayList which contains object from servlet to JSP. But

Servlet file:

request.setAttribute("servletName", categoryList); //categorylist is an arraylist      contains object of class category  
getServletConfig().getServletContext().getRequestDispatcher("/GetCategory.jsp").forward(request,response);

JSP file:

//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() );
}
%>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
468 views
Welcome To Ask or Share your Answers For Others

1 Answer

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());
}
%>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...