如何以表格格式显示 ArrayList? [英] How to display an ArrayList in tabular format?

查看:39
本文介绍了如何以表格格式显示 ArrayList?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 Servlet 代码中有一个 ArrayList.现在,我想以表格格式显示 ArrayList.我怎样才能做到这一点?

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

例如

ArrayList dataList = new ArrayList();

// dataList Add Item

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

推荐答案

表格在 HTML 中由

元素表示.您应该为 HTML 代码使用 JSP 以将视图与控制器分开(这将大大提高可维护性).您可以使用 JSTL 来控制 JSP 中的流程.您可以使用 JSTL <c:forEach> 标签来迭代一个集合.

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.

在 servlet 中,将列表放入请求范围并转发到 JSP:

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);

/WEB-INF/dataList.jsp中,可以用HTML

表示,如下:

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>

另见: