Passing ArrayList from servlet to JSP

I am trying to pass an ArrayList that contains an object from a servlet to a 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() ); } %> 
+7
java arraylist jsp servlets
source share
4 answers

In the servlet code with the request.setAttribute("servletName", categoryList) instruction request.setAttribute("servletName", categoryList) you save your list in the request object and use the name "servletName" to refer to it.
By the way, using the name "servletName" for a list is pretty confusing, maybe it's better to call it a "list" or something similar: request.setAttribute("list", categoryList)
In any case, suppose you do not change your servlet code and save the list using the name "servletName". When you come to JSP, you need to get a list from the request, and for this you only 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()); } %> 
+13
source share

request.getAttribute("servletName") returns the Object you need to pass to ArrayList

 ArrayList<Category> list =new ArrayList<Category>(); //storing passed value from jsp list = (ArrayList<Category>)request.getAttribute("servletName"); 
+4
source share

possible errors will be ...
1.You set the list of arrays from the servlet in the session, not in the request.
2. The selected array is zero.
3. You redirect the page, not forward it.

also you should not initialize list and category in jsp. try this.

 for(Category cx: ((ArrayList<Category>)request.getAttribute("servletName"))) { out.println( cx.getId()); out.println(cx.getName()); out.println(cx.getMainCategoryId() ); } 
0
source share

here the name of the attribute of the list list in the request request.setAttribute("List",list); and ArrayList list=new ArrayList();

 <% ArrayList<Category> a=(ArrayList<Category>)request.getAttribute("List"); out.print(a); for(int i=0;i<a.size();i++) { out.println(a.get(i)); } %> 
-2
source share

All Articles