Search code examples
javaforeachjstl

Populate JSP table with JSTL forEach Loop


My program takes an email from input, and uses the haveibeenpwned API to show the user all the breaches found from that email.

I'm wondering how I can get my forEach loop to populate a table properly. Currently, it just populates every item into one table row with the table header below the data. I would like the header to be on top, and each breach to be in a separate table row.

Here is my .jsp form showing the table and forEach:

<table class="table">
  <thead>
    <tr>
      <th scope="col">#</th>
      <th scope="col">Breach</th>
    </tr>
  </thead>
  <tbody>
    <c:forEach var="breach" items="${breaches}" varStatus="status">
      <tr>
        <th scope="row">${status.count}</th>
          <td><p>${breach}</p></td>
      </tr>
    </c:forEach>
  </tbody>
</table>

Here is my servlet where I get an ArrayList of found breaches:

String json = callPwnedApi(email);

    if (json.startsWith("{") || json.startsWith("[")) {
        Gson gson = new Gson();
        ArrayList<Breach> breaches = gson.fromJson(json, new TypeToken<ArrayList<Breach>>(){}.getType());

        if (!breaches.isEmpty() && breaches.size() > 0) {
            request.setAttribute("breaches", breaches);
        }
    } 

Solution

  • So being new to JSTL, I made a very simple mistake!

    I wasn't aware I needed to add the JSTL library to my project, and I also needed to add this line to my .jsp page:

    <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
    

    So after doing this, my table works perfectly! Hopefully this will eventually help out someone new to JSTL!