在 簡單的表格
中曾經提過,<h:dataTable>可以列舉以下幾種型態的資料:
- 陣列
- java.util.List的實例
- java.sql.ResultSet的實例
- javax.servlet.jsp.jstl.sql.Result的實例
- javax.faces.model.DataModel的實例
對於前四種型態,JSF實際上是以javax.faces.model.DataModel加以包裝,DataModel是個抽象類別,其子類別都是位於
javax.faces.model這個package下:
- ArrayDataModel
- ListDataModel
- ResultDataModel
- ResultSetDataModel
- ScalarDataModel
如果您想要對表格資料有更多的控制,您可以直接使用DataModel來設定表格資料,呼叫DataModel的setWrappedObject()方
法可以讓您設定對應型態的資料,呼叫getWrappedObject()則可以取回資料,例如:
package onlyfun.caterpillar; import java.util.*; import javax.faces.model.DataModel; import javax.faces.model.ListDataModel; public class TableBean { private DataModel model; private int rowIndex = -1; public DataModel getUsers() { if(model == null) { model = new ListDataModel(); model.setWrappedData(getUserList()); } return model; } private List getUserList() { List userList = new ArrayList(); userList.add(new UserBean("caterpillar", "123456")); userList.add(new UserBean("momor", "654321")); userList.add(new UserBean("becky", "7890")); return userList; } public int getSelectedRowIndex() { return rowIndex; } public String select() { rowIndex = model.getRowIndex(); return "success"; } }
在這個Bean中,我們直接設定DataModel?,將userList設定給它,如您所看到的,我們還可以取得DataModel?的各個變項,在這
個例子中,select()將作為點選表格之後的事件處理方法,我們可以藉由DataModel?的getRowIndex
()來取得所點選的是哪一row的資料,例如:
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %> <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %> <html> <link href="styles.css" rel="stylesheet" type="text/css"/> <body> <f:view> <h:form> <h:dataTable value="#{tableBean.users}" var="user" styleClass="orders" headerClass="ordersHeader" rowClasses="evenColumn,oddColumn"> <h:column> <f:facet name="header"> <h:outputText value="Name"/> </f:facet> <h:commandLink action="#{tableBean.select}"> <h:outputText value="#{user.name}"/> </h:commandLink> <f:facet name="footer"> <h:outputText value="****"/> </f:facet> </h:column> <h:column> <f:facet name="header"> <h:outputText value="Password"/> </f:facet> <h:outputText value="#{user.password}"/> <f:facet name="footer"> <h:outputText value="****"/> </f:facet> </h:column> </h:dataTable> </h:form> Selected Row: <h:outputText value="#{tableBean.selectedRowIndex}"/> </f:view> </body> </html>
DataModel的rowIndex是從0開始計算,當處理ActionEvent時,JSF會逐次遞增rowIndex的值,這讓您可以得知目前正在處理的是哪一個row的資料,一個執行的圖示如下:
|