user6373874
user6373874

Reputation:

(JSP2-MVC) How to iterate an arraylist of java bean?

I am looking for a way to iterate over an arraylist of java beans in a jsp2 page.

I have a bean "catalog" with an arraylist of beans "items" and for each bean

I get it with: ${catalog.items}; I need to display each item as a <li></li>.

What is the correct way of doing this iteration in jsp2 MVC project without other older or newer framework, just JSP2 respecting MVC?

Upvotes: 0

Views: 690

Answers (2)

Taha
Taha

Reputation: 1242

The answer above not respecting MVC

<li>---</li> 

must be written in the VUE and not in the MODEL(BEAN)

I think you want to display your list in a jsp page using MVC architecture the way is :

1/add a function that return a list in your bean (Model)

2/a servlet that instantiate this bean and call this function and set this list in request (controller)

3/the jsp page desplay the list (view)

this is an example : 1/Bean :

add this funtion :

public List<items> loadList() {
     List<items> Mylist = new ArrayList<tests>();

    //Your code to fill the list 

  return Mylist;

    } 

2/Servlet :

public class ExampleServlet extends HttpServlet {


    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {


                catalog MyObject = new catalog();


       try {
            List<items> list = MyObject.loadList();

        request.setAttribute("recolist", list);

        RequestDispatcher view = request.getRequestDispatcher("My.jsp");
        view.forward(request, response); 


         } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }


    }}

3/ JSP -My.jsp- : add this code to your JSP page

<c:forEach var="VAR" items="${recolist}">

<li>${VAR./*WHAT YOU WANT*/}</li>                                                           
</c:forEach>

Note that VAR is a items object you can call any attribute of the object items for example id , name ...

Upvotes: 1

Billy Ng
Billy Ng

Reputation: 28

You can write a method in your bean class (catalog), just like:

public String getItemsList()
{
    String printlist = "";
    for(item i:items)//object you want to loop
    {
        printlist = "<li>xxxxxxxxxx</li>";
        ........
    }
    return printlist;
}

Then, change ${catalog.items} to ${catalog.itemsList} in your jsp page.

I hope this helps you.

Upvotes: 0

Related Questions