Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

jsp

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.

like image 920
LGAP Avatar asked Dec 27 '11 15:12

LGAP


People also ask

What is the use of include () method in JSP?

The include directive is used to include a file during the translation phase. This directive tells the container to merge the content of other external files with the current JSP during the translation phase.

How do I view a JSP file?

Right-click the index. jsp file; click Run As > Run on Server. The storefront page is displayed in the Web browser. Note: If prompted to select a server, select Choose an existing server and click Finish.


1 Answers

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?
like image 73
BalusC Avatar answered Sep 28 '22 10:09

BalusC