How To Color Alternate Lines in JSP Databound Table

Written by Duncan Mills, Oracle Corporation
January 2004


With long lists of read only data presented in tabular form, it is a common requirement that alternate lines on a table are colored differently to help users read the output. The following illustration shows the kind of effect that this document describes:

Implementing Alternating Line Colors

When you use the Data Control palette to create a tabular layout in a data bound page, a JSTL <c:forEach> tag is created to loop through the set of rows. To color alternate rows we can leverage a handy facility of the <c:forEach> tag which is it's varStatus attribute. The varStatus attribute allows you to define the name of a local variable in the page which will receive status information about the <c:forEach> loop and the current iteration of it. This status object contains useful information about the loop including a property called count. This count property gives a 1 based index number of the current loop, so we can use that in a simple expression, if the count is an odd number we use one color for the table row, if it is an even number we use another. Note that this technique is based on generic JSTL tag functionality, and so it's use is not restricted to databound JSP pages, but can be applied for any <c:forEach> tag.

Setting varStatus

To set the status variable up you can either add the attribute directly to the <c:forEach> tag, or you can select the <c:forEach> tag in the structure pane and set the value directly in the property palette. In this case we'll use a status variable called lineInfo.

This will result in a tag of:

<c:forEach var="Row" items="${bindings.EmpView1.rangeSet}" varStatus="lineInfo">

Using the status variable

So we have the lineInfo object which has a count property to reflect the current line number in the range. To use that value we can use another JSTL expression <c:choose> to generate different <TR> tags depending on if the count value is odd or even.

Replace the opening <TR> tag inside the <c:forEach> loop with the following code:

   <c:when test="${lineInfo.count % 2 == 0}">
     <tr bgcolor="#ffffcc"> 
<tr bgcolor="#ffffff">
</c:otherwise> </c:choose>

In this example, we are just hard-coding bgcolor attribute into the table row tags, however, in most cases you would want to use a style sheet, perhaps with special TR.odd and TR.even definitions to color the lines. In that case you would, in that case specify the class attribute for the <TR> tag instead.

false ,,,,,,,,,,,,,,,