Lucky Dip Logo
Powered by PlusNet. PlusNet broadband.
Patrick's Lucky Dip
Home > Java > HTML Tables from Java Recordsets

Patrick Haston
15 April 2009

HTML Tables from Java Recordsets

The Problem

It's quite straightforward to create an html table from a recordset when you know what columns are in the select statement, but here's a trick I saw that you can use to create a table from any recordset.

The Solution

The basis of this is to use the ResultSetMetaData class to establish what columns are in the RecordSet. These then become the column headings.

Here's it in practice:

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;

public class Report 
{
  private String row_class = "row_odd"; // alternates between row_odd and row_even

  public Report()
  {
  }
  
  /**
   * Takes the ResultSet that is passed in and returns the html code to display it as a table.
   * @throws java.lang.Exception
   * @return the html table for this report of css class "report"
   * @param rs - the result set to display
   */
  public String getReport( ResultSet rs ) throws Exception
  {
    ResultSetMetaData rsmd = rs.getMetaData();
    String html = "<table class='report'>\n";
    
    html = html + " <tr>\n";
    for(int i=1; i <= rsmd.getColumnCount() ; i++)
    {
      html = html + "  <th>" + rsmd.getColumnLabel(i) +"</th>\n";
    }
    html = html + " </tr>\n";
    
    while( rs.next() )
    {
      html = html + " <tr class='" + row_class + "'>\n";
      for(int i=1; i <= rsmd.getColumnCount() ; i++)
      {
        String s = rs.getString(i);
        if( s == null ) s = " ";
        html = html + "  <td>" + s +"</td>\n";
      }
      html = html + " </tr>\n";

      // switch the row class for the next row
      if( row_class.equalsIgnoreCase("row_odd") ) row_class = "row_even";
      else row_class = "row_odd";
    }
    html = html + "</table>\n";

    return html;
  }
}

If you include this css file in your jsp page then you have a core of a useful utility:

.report table
{
  background: #dff;
}

.report th
{
  background: #cee;
  text-align: left;
}

.report td
{
}

.row_odd
{
  background: #eff;
}

.row_even
{
  background: #dff;
}

That's all there is to it.