使用JSTL标签和EL表达式实现隔行显示不同颜色的效果

在Servlet文件中:

ArrayList db_list = new ArrayList();

Student db_Student1 = new Student();

db_Student1.setUsername("gaohongyan1");

Student db_Student2 = new Student();

db_Student2.setUsername("gaohongyan2");

Student db_Student3 = new Student();

db_Student3.setUsername("gaohongyan3");

Student db_Student4 = new Student();

db_Student4.setUsername("gaohongyan4");

Student db_Student5 = new Student();

db_Student5.setUsername("gaohongyan5");

db_list.add(db_Student1);

db_list.add(db_Student2);

db_list.add(db_Student3);

db_list.add(db_Student4);

db_list.add(db_Student5);

request.setAttribute("db_list", db_list);

在JSP文件中:

隔行显示不同的颜色:

<br />

<table width="200" border="1">

  <tr bgcolor="#FF0000">

             <td width="89">

                        <div align="center">

                                   id

                        </div>

             </td>

             <td width="95">

                        <div align="center">

                                   value

                        </div>

             </td>

  </tr>

  <c:forEach items="${db_list}" var="db_bean" varStatus="status_var">

             <c:if test="${status_var.index % 2 ==0}">

                        <tr>

                                   <td>

                                              ${status_var.index+1}

                                   </td>

                                   <td>

                                              ${db_bean['username'] }

                                   </td>

                        </tr>

             </c:if>

             <c:if test="${status_var.index % 2 !=0}">

                        <tr bgcolor="#999999">

                                   <td>

                                              ${status_var.index+1}

                                   </td>

                                   <td>

                                              ${db_bean['username'] }

                                   </td>

                        </tr>

             </c:if>

  </c:forEach>

</table>

这个效果主要是使用了c:forEach标签中的varStatus属性来获取。隔行显示不同颜色的原理主要是 index为奇数或偶数,这就需要在每次遍历时将当前显示的index的索引值取出来,再用<c:if>标签进行判断,就可以实现隔行显示不同颜色的效果了。

显示结果如图10-2所示。

使用JSTL标签和EL表达式实现隔行显示不同颜色的效果


图10-2  隔行显示不同的颜色

你可能感兴趣的:(Web,jsp,css)