Madi
Madi

Reputation: 55

Looping through List<HashMap<String,Object>> in JSP

I have a java method that returns me contact information from database table and I am saving each record in a List as a HashMap (List<HashMap<String,Object>>). Each HashMap comprises of almost 10 key value pairs(firstName, lastName, PhoneNumber, officeLocation etc). I want to use this List to populate a HTML table in JSP using loop. But not sure how to do that. Tried look for possible solutions on google, but didnt find a good solution.

Scrptlet in my JSP:

<jsp:scriptlet>
     PhoneListController controller = new PhoneListController();
     List<HashMap<String, Object>> totalResults = controller.getDataToDisplay();
     request.setAttribute("contactsList", totalResults);
</jsp:scriptlet>       

Please guide how do i proceed after this in JSP.

Thanks.

Upvotes: 1

Views: 1799

Answers (1)

JB Nizet
JB Nizet

Reputation: 691635

You do it the same way as for any other list, using the JSTL forEach tag:

<c:forEach var="map" items="${contactsList}">
    <tr>
        <td><c:out value="${map['firstName']}"/>
        <td><c:out value="${map['lastName']}"/>
        ...
    </tr>
</c:forEach>

A few notes:

  • scriptlets are obsolete and considered bad practice for more than 10 years. Don't use scriptlets. Use the JSTL and the JSP EL. The code you posted in the question should be inside a controller servlet.
  • Why use a HashMap to store contact information. You should define a Java Bean class named Contact, and return a List<Contact>. Java is an OO language. Define and use objects.

Upvotes: 2

Related Questions