如何将列数未知的 ResultSet 映射到 List 并将其显示在 HTML 表中? [英] How to map a ResultSet with unknown amount of columns to a List and display it in a HTML table?

查看:16
本文介绍了如何将列数未知的 ResultSet 映射到 List 并将其显示在 HTML 表中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 Netbeans、GlassFish 和 JavaDB 创建了一个数据库应用程序.现在我的控制器 Servlet 代码执行一些动态 SQL 查询并返回结果集(或者我可以更改为字符串).现在,如何以表格格式显示返回的结果集(我不知道结果集的结构).有人可以帮我解决这个问题吗?

I have created a Database Application using Netbeans, GlassFish and JavaDB. Now my controller Servlet code executes some dynamic SQL queries and get back a Result Set (or I can ahange toString). Now, how can I show the returned Result Set in a tabular format ( I have no idea about structure of result set). Can anybody help me about this ?

推荐答案

您可以使用 Map 表示一个动态"行,即iterable.您可以使用 ResultSetMetaData 收集有关列的信息,例如 列数列标签.

You can use Map<String, Object> to represent a "dynamic" row, which is iterable in <c:forEach>. You can use ResultSetMetaData to collect information about the columns such as the column count and the column labels.

所以,这个映射应该:

List<Map<String, Object>> rows = new ArrayList<Map<String, Object>>();
ResultSetMetaData metaData = resultSet.getMetaData();
int columnCount = metaData.getColumnCount();

while (resultSet.next()) {
    Map<String, Object> columns = new LinkedHashMap<String, Object>();

    for (int i = 1; i <= columnCount; i++) {
        columns.put(metaData.getColumnLabel(i), resultSet.getObject(i));
    }

    rows.add(columns);
}

可以在JSP中显示如下:

You can display it in JSP as follows:

<table>
  <thead>
    <tr>
      <c:forEach items="${rows[0]}" var="column">
        <td><c:out value="${column.key}" /></td>
      </c:forEach>
    </tr>
  </thead>
  <tbody>
    <c:forEach items="${rows}" var="columns">
      <tr>
        <c:forEach items="${columns}" var="column">
          <td><c:out value="${column.value}" /></td>
        </c:forEach>
      </tr>
    </c:forEach>
  </tbody>
</table>

这篇关于如何将列数未知的 ResultSet 映射到 List 并将其显示在 HTML 表中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆