How to iterate over a list of objects in jsp / How to create a table from a list of objects in jsp / How to iterate over a collection using jstl

Scenario
Suppose we want to show a list of registered users of the application in a tabular format on a jsp. The list of users is created on the server and is bound to an attribute (in request, session or application scope) if you are using servlet or bound to an attribute in ModelAndView if you are using Spring controller as below.

    List userList = new ArrayList();
    /* the list is populated by fetching data from database using DAO layer here */
    //add list to a request object if you are using servlet
    request.setAttribute("users", userList);
    //add object to model in Spring controller
    modelAndView.addObject("users", userList);

The list “userList” consists of objects of User class which looks like:

  public class User {
     private String name;
     private String country;
     //getters and setters
  }

Now we have to populate a table (in HTML) out of the User objects set in the userList present in the request or model object in the jsp. How to do that?  Read On !!!

How to iterate over the list
An HTML table consists of multiple rows(elements) and each row has multiple columns (elements). If we relate it with the user list using which the table needs to be created, then

each list object will be a row and properties of that object will be columns of this table.
Keeping this thought in mind, if we iterate over the userList object, then a row will be created in every iteration and the columns of this row will be the properties of the User object we get from the userList object in every iteration.

There are two ways of iterating over a collection in jsp.

1. Traditional for loop using scriptlet elements
Scriptlet is a jsp element which is used to embed java code in a jsp. Its symbol is <% %>. Java code is written between these tags. For iterating our list using scriptlet, the following code will be required:

      

<% ArrayList users = (ArrayList)request.getAttribute(“userList”); for (int i = 0; i < users.size(); i++) { User user = users.get(i); %>
<% } %>

<% out.print(user.getName()); %> <% out.print(user.getLocation()); %>

 

2. forEach tag using jstl (JSP Standard Tag Library)
Iterating over a collection using jstl is far more easier than using scriptlets. jstl expressions start with a $ symbol surrounded by curly braces ({ }) and use a “.” (dot operator) for accessing the properties of an object. jstl supports a forEach loop to iterate over collections and here is how:

   
  

${user.name} ${user.location}

 

See, how compact and clean the code looks in jstl. The “var” attribute holds the reference to the object in the current iteration of the loop and “items” attribute holds the collection to be iterated and its value must match the name with which the collection is stored in a scope.

Both of the above approaches will create a table in the html page generated out of this jsp and would look like:

Name Location
Codippa India
Google California
Facebook Amsterdam

So we have created a table by iterating over a collection stored as an attribute in any scope on jsp.

Let’s tweak in

  1. The POJO class whose objects are the members of a collection to be iterated should have proper getter and setter methods for its fields as when accessing a property name using jstl’s dot operator, the corresponding setter method of that property is invoked.
  2. For using jstl tags, we need to import its tag library in jsp. This is done by providing a declaration <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> at the start of jsp.
  3. When using any java class in scriptlet code, the class needs to be imported in jsp just as we do in a java file. In the above example we used java.util.ArrayList class, so we must add a declaration as <%@ page import="java.util.ArrayList" %> in our jsp file.
  4. Use of scriptlets in jsp is highly discouraged since jsps are best suited as a view and they should not contain java code.
If you liked the article or it helped you out, do not forget to click the clap below.

4 Comments


Leave a Reply