很多資料經常使用表格來表現,JSF提供<h:dataTable>標籤讓您得以列舉資料並使用表格方式來呈現,舉個實際的例子來看,假設您撰寫了以下:
- UserBean.java
package onlyfun.caterpillar;
public class UserBean {
private String name;
private String password;
public UserBean() {
}
public UserBean(String name, String password) {
this.name = name;
this.password = password;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
- TableBean.java
package onlyfun.caterpillar;
import java.util.*;
public class TableBean {
private List userList;
public List getUserList() {
if(userList == null) {
userList = new ArrayList();
userList.add(
new UserBean("caterpillar", "123456"));
userList.add(
new UserBean("momor", "654321"));
userList.add(
new UserBean("becky", "7890"));
}
return userList;
}
}
在TableBean中,我們假設getUserList()方法實際上是從資料庫中查詢出UserBean的內容,之後傳回List物件,若我們的 faces-config.xml如下:
- faces-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE faces-config PUBLIC "-//Sun Microsystems,
Inc.//DTD JavaServer Faces Config 1.0//EN"
"http://java.sun.com/dtd/web-facesconfig_1_0.dtd">
<faces-config>
<managed-bean>
<managed-bean-name>tableBean</managed-bean-name>
<managed-bean-class>
onlyfun.caterpillar.TableBean
</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
</managed-bean>
<managed-bean>
<managed-bean-name>userBean</managed-bean-name>
<managed-bean-class>
onlyfun.caterpillar.UserBean
</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
</managed-bean>
</faces-config>
我們可以如下使用<h:dataTable>來產生表格資料:
- index.jsp
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
<html>
<body>
<f:view>
<h:dataTable value="#{tableBean.userList}" var="user">
<h:column>
<h:outputText value="#{user.name}"/>
</h:column>
<h:column>
<h:outputText value="#{user.password}"/>
</h:column>
</h:dataTable>
</f:view>
</body>
</html>
<h:dataTable>的value值綁定tableBean的userList方法,它會一個一個取出 List中的資料並設定給var設定的user,之後在每一個column中我們可以顯示所列舉出的user.name與user.password,程 式的結果會如下所示:
所產生的HTML表格標籤如下:
<table>
<tbody>
<tr>
<td>caterpillar</td>
<td>123456</td>
</tr>
<tr>
<td>momor</td>
<td>654321</td>
</tr>
<tr>
<td>becky</td>
<td>7890</td>
</tr>
</tbody>
</table>
<tbody>
<tr>
<td>caterpillar</td>
<td>123456</td>
</tr>
<tr>
<td>momor</td>
<td>654321</td>
</tr>
<tr>
<td>becky</td>
<td>7890</td>
</tr>
</tbody>
</table>
<h:dataTable>的value值綁定的對象可以是以下的型態:
- 陣列
- java.util.List的實例
- java.sql.ResultSet的實例
- javax.servlet.jsp.jstl.sql.Result的實例
- javax.faces.model.DataModel的實例