How to map a ResultSet with unknown amount of columns to a List and display it in a HTML table?

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 ( {
    Map<String, Object> columns = new LinkedHashMap<String, Object>();

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


You can display it in JSP as follows:

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

Leave a Comment