How to Display List Contents in tabular format in a JSP file?

java, jsp

Solution

Use HTML `<table>` element to represent a table in HTML. Use JSTL `<c:forEach>` to iterate over a list in JSP.

E.g.

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
...
<table>
  <c:forEach items="${list}" var="item">
    <tr>
      <td><c:out value="${item}" /></td>
    </tr>
  </c:forEach>
</table>

You've only a design flaw in your code. You've split related data over 2 independent lists. It would make the final approach as ugly as

<table>
  <c:forEach items="${TAREWEIGHT}" var="tareWeight" varStatus="loop">
    <c:set var="barCode" value="${BARCODE[loop.index]}" />
    <tr>
      <td><c:out value="${tareWeight}" /></td>
      <td><c:out value="${barCode}" /></td>
    </tr>
  </c:forEach>
</table>

I suggest to create a custom class to hold the related data together. E.g.

public class Product {

    private BigDecimal tareWeight;
    private String barCode;

    // Add/autogenerate getters/setters/equals/hashcode and other boilerplate.
}

so that you end up with a `List<Product>` which can be represented as follows:

<table>
  <c:forEach items="${products}" var="product">
    <tr>
      <td><c:out value="${product.tareWeight}" /></td>
      <td><c:out value="${product.barCode}" /></td>
    </tr>
  </c:forEach>
</table>

after having put it in the request scope as follows:

request.setAttribute("products", products);

See also:

- Our JSTL wiki page

- How to avoid Java code in JSP files?

Problem

In an Action.java file, am using the following piece of code. ``` request.setAttribute("TAREWEIGHT", tareWeightList); request.setAttribute("BARCODE", barcodeList); return (mapping.findForward(target)); ``` tareWeightList & barcodeList actually holds few values. After setting the list values to the attributes, the java file forwards the contents to a JSP file. There in JSP file, I can get the contents using below lines, ``` <%=request.getAttribute("TAREWEIGHT")%> <%=request.getAttribute("BARCODE") %> ``` My requirement is that the contents of that lists should be diplayed in a tabular format. Barcode values in first column and its corresponding Tareweight values in the second column. Suggest me an idea for writing the code in JSP file so as the contents are displayed in a tabulated format.

Original source

Related problems