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

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

问题描述

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

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< String,Object> 代表动态行,即可迭代 c为C:的forEach> 。您可以使用 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.

所以,这个映射应该这样做:

So, this mapping should do:

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天全站免登陆