简体   繁体   中英

How to display an ArrayList in tabular format?

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

Eg

ArrayList dataList = new ArrayList();

// dataList Add Item

out.println("<h1>" + dataList  +"</h1>"); // I want to view it in tabular format.

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:

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!!!

您将不得不使用HTML表而不是H1元素,遍历对象列表并打印其属性

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM