论坛首页 Java企业应用论坛

JSF的表设计

浏览 2066 次
锁定老帖子 主题:JSF的表设计
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2009-04-18   最后修改:2009-04-26
TableModel类
<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()则可以取回数据,例如:
• TableBean.java
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的数据,例如:
index.jsp
<%@ 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的数据.
论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics