---
title: "c:forEach标签 多次查询数据库"
author: "origin100"
date: "2009-09-10T14:32:08Z"
tags: []
slug: "c-foreach"
draft: false
lastmod: "2009-09-10T14:32:08Z"
id: 466245
url: "https://origin100.iteye.com/blog/466245"
---

这几天比较郁闷，项目页面用JSF组件展现，朋友的功能中需要循环展示一个div，引用了c标签forEach循环输出，forEach比较讨厌的会多次调用items方法访问数据库。在网上看到一个巧妙的做法，在方法上加了一个判断，现在记录如下：



```java
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> //导入的是JSTL 1.1 core Library
......
<table>
    <tr>
        <th>Item Name</th>
    </tr>
   <c:forEach items="#{Backbean.showKind}" var="k">  //item=List类型
    <tr>
         <td><h:outputText value="#{k.nowsum}" /><td>
    </tr>
    </c:forEach>
</table>
......
```


bean:
//用forEach循环中控制控件,会多次调用 items 方法访问数据库,所以需定义一个判断.

```java
 public List getShowKind() {
  if (null==showKind){
   //...得到showKind的业务逻辑
  }
    return showKind;
  
 } 
```