Mohamed Shakir
Mohamed Shakir

Reputation: 43

Converting an ArrayList<someObjects> to an HTML table

I have a couple of ArrayLists with variable length and sometimes null. This ArrayList contains a bunch of objects. The table should have columns based on (some) attributes of the object. And the table should be displayed on a jsp.

I have two ideas, one is to use a JSTL tag the other is to use JavaScript. And library suggestions are welcome.

Upvotes: 0

Views: 7182

Answers (3)

Bozho
Bozho

Reputation: 597076

JSTL is the standard, preferred way (unless you need to load it via ajax, for example)

<table>
<tr><td>Foo header</td><td>Bar header</td></tr>
<c:forEach items="${yourRequestScopedArrayList}" var="obj">
    <tr>
       <td>${obj.foo}</td>
       <td>${obj.bar}</td>
    </tr>
</c:forEach>
</table>

Upvotes: 1

Stephen P
Stephen P

Reputation: 14800

Javascript doesn't have access to the Java objects that live (I presume) on the server. The server code can make the ArrayLists available to the JSP which can then loop over them with a JSTL forEach tag.

How you make the ArrayLists "available" depends on the framework you're using, but the plain servlet way is just setting an attribute from the doPost method.

request.setAttribute("list1", arrayList1);

The loop would be something like

<table>
<tr><th>Column 1</th> <th>Column 2</th> <th>Column 3</th></tr>
<c:forEach var="row" items="${list1}">
    <tr><td>${row.col1data}</td> <td>${row.col2data}</td> <td>${row.col3data}</td></tr>
</c:forEach>
</table>

Upvotes: 0

Jigar Joshi
Jigar Joshi

Reputation: 240880

JSTL is better,

Javascript you should avoid as much as possible ,

I am not sure how you are going to render datatable using java script and Collection

How to use jstl with collection that has been demonstrated by Bozho in the same thread.

Upvotes: 0

Related Questions