JSTL Query Results Jumble!!!
Hello Everybody!!
I am new to JSTL and I thought I would try to do a simple query and then print out the results.....unfortunately, much to my dismay, the headers (column names) printed out in the correct order....but the foreach tags seem to be playing a mean game of jumble on my results....meaning they are not even close to the order in which I selected them in .....below is the code I use to print out the results.....
<%// construct table of returned values %>
<table bgcolor="gray">
<%-- Get the column namesfor the header of the table --%>
<tr bgcolor="#295AA5">
<c:forEach var="columnName" items="${RecordSet.columnNames}">
<th><c:out value="${columnName}"/></th>
</c:forEach>
</tr>
<%-- Get the value of each columnwhile iterating over rows --%>
<%int alt_row = 0;//needed for alternating rows %>
<c:forEach var="row" begin="0" items="${RecordSet.rows}">
<%if(alt_row % 2 == 0)
out.println("<tr bgcolor=\"#CCCCCC\">");
else
out.println("<tr bgcolor=\"#EEEEEE\">");
%>
<c:forEach var="column" items="${row}">
<td> <c:out value="${column.value}"/> </td>
</c:forEach>
</tr>
<% alt_row++; %>
</c:forEach>
</table>
[1997 byte] By [
Phil1982a] at [2007-10-2 14:31:07]

Rewriting to get rid of ugly scriptlet code.
Introducing the varStatus variable: It keeps track of useful things like the index/count of the current record. You can then use it with the JSTL conditional tags.
The other issue: use rowsByIndex rather than the rows property.
rowsByIndex returns the columns in the same order as the columnNames property did. rows returns a Map of columnNames, sorted alphabetically by column name. You can understand why they don't print in the same order ;-)
Also, rather than using bgcolor, I am a fan of using css style sheets, so I would probably use a class="" rather than specifying the colour directly in the JSP. But each to their own.
<%-- construct table of returned values -- %>
<table bgcolor="gray">
<%-- Get the column names for the header of the table --%>
<tr bgcolor="#295AA5">
<c:forEach var="columnName" items="${RecordSet.columnNames}">
<th><c:out value="${columnName}"/></th>
</c:forEach>
</tr>
<%-- Get the value of each column while iterating over rows --%>
<c:forEach var="row" items="${RecordSet.rowsByIndex}" varStatus="status">
<c:choose>
<c:when test="${status.index % 2 == 0}">
<tr bgcolor="#CCCCCC">
</c:when>
<c:otherwise>
<tr bgcolor="#EEEEEE">
</c:otherwise>
<c:forEach var="column" items="${row}">
<td> <c:out value="${column.value}"/> </td>
</c:forEach>
</tr>
</c:forEach>
</table>
Cheers,
evnafets