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() );
}
%>
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());
}
%>
request.getAttribute("servletName")
method will return Object
that you need to cast to ArrayList
ArrayList<Category> list =new ArrayList<Category>();
//storing passed value from jsp
list = (ArrayList<Category>)request.getAttribute("servletName");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With