0

I have an ArrayList in my Servlet code. Now, I want to show that ArrayList in a tabular format. How can I achive this?

E.g.

ArrayList dataList = new ArrayList();

// dataList Add Item

out.println("<h1>" + dataList  +"</h1>"); // I want to view it in tabular format.
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
alessandro
  • 1,681
  • 10
  • 33
  • 54

3 Answers3

3

Tables are in HTML to be represented by <table> element. You should be using JSP for HTML code to separate view from the controller (which will greatly increase maintainability). You could use JSTL to control the flow in JSP. You can use JSTL <c:forEach> tag to iterate over a collection.

In the servlet, put the list in the request scope and forward to a JSP:

request.setAttribute("dataList", dataList);
request.getRequestDispatcher("/WEB-INF/dataList.jsp").forward(request, response);

In the /WEB-INF/dataList.jsp, you can present it in a HTML <table> as follows:

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
...
<table>
    <c:forEach items="${dataList}" var="dataItem">
        <tr>
            <td>${dataItem.someProperty}</td>
            <td>${dataItem.otherProperty}</td>
        </tr>
    </c:forEach>
</table>

See also:

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • but thats JSP (i know its a better option) in servlet you would have to use regular java loop and print the rows with out.println() – Kris Feb 03 '12 at 15:11
  • @Kris: as you said yourself, this would be the wrong way. I am the last who would recommend bad practices to anyone who will get big regret of the approach after some time because they end up with unmaintainable code. Just do it the right way from the beginning on :) – BalusC Feb 03 '12 at 15:13
1

See below how ArrayList works

out.println("<table>");
ArrayList dataList = new ArrayList();
// add some data in it....
for (Iterator iter = dataList.iterator(); iter.hasNext();) {
    out.println("<tr><td>" + (String)(iter.next()) + "</td></tr>");
}
out.println("</table>");

Good Luck!!!

Fahim Parkar
  • 30,974
  • 45
  • 160
  • 276
0

You would have to go with HTML Tables instead of H1 elements, iterate through the list of objects and print their properties

Kris
  • 5,714
  • 2
  • 27
  • 47