列的filterCell屬性控制過濾器如何顯示,它和cell屬性非常相像并且也是實現Cell接口。馬上要定義的是默認的和droplist這兩個過濾器cells。
默認的是一個輸入框元素而droplist是一個下拉列表元素。當然,如果你需要進行一些定制你可以插接自己的實現。
最近,我被問到是否能夠實現一個過濾器cell,顯示已經通過別的過濾器過濾得到數據子集。答案當然是肯定的,而且這是我將在這里示范的。通常定制的
cell可以很容易被創建,這個示例將印證這點。在這個示例里last name列里顯示的將是通過first name過濾后的子集。如果沒有通過
first name過濾那么所有值都將被顯示。
通常你只需要為過濾器cell實現Cell接口。然而,因為我們要創建的過濾器cell是一個下拉列表,我們可以通過擴展
FilterDroplistCell來獲得它已經提供的很多功能,FilterDroplistCell是發行包已經提供的cells之一。
我們需要覆蓋FilterDroplistCell的唯一方法是getFilterDropList()。這是整個類的全部代碼:
public class FilteredDroplistCell extends FilterDroplistCell {
private static Log logger = LogFactory.getLog(FilterDroplistCell.class);
protected List getFilterDropList(TableModel model, Column column) {
List droplist = new ArrayList();
String firstNameFilter = model.getLimit().getFilterSet().getValue("firstName");
Collection beans = model.getCollectionOfBeans();
for (Iterator iter = beans.iterator(); iter.hasNext();) {
Object bean = iter.next();
try {
String firstName = BeanUtils.getProperty(bean, "firstName");
if (StringUtils.isNotBlank(firstNameFilter) && !firstName.equals(firstNameFilter)) {
continue;
}
String lastName = BeanUtils.getProperty(bean, column.getProperty());
if ((lastName != null) && !droplist.contains(lastName)) {
droplist.add(lastName);
}
} catch (Exception e) {
logger.debug("Problems getting the droplist.", e);
}
}
Collections.sort(droplist);
return droplist;
}
}
如果你比較這個類和父類,你會發現它們只有微小的區別。
首先需要注意的是我們需要找出first name是否已經被過濾了。
String firstNameFilter = model.getLimit().getFilterSet().getValue("firstName");
然后我們需要判斷當前bean的first name值是否和first name過濾器值相同。如果相同,將當前的last name值
添加到droplist中。
String firstName = BeanUtils.getProperty(bean, "firstName");
if (StringUtils.isNotBlank(firstNameFilter) && !firstName.equals(firstNameFilter)) {
continue;
}
如果last
name將添加到droplist中,我們需要檢查droplist中是否已經包含了這個值。如果沒有,我們就把它添加到droplist中。
String lastName = BeanUtils.getProperty(bean, column.getProperty());
if ((lastName != null) && !droplist.contains(lastName)) {
droplist.add(lastName);
}
為了使用這個Cell你應該在Preferences中聲明一個別名。
當然,你可以省略這步而在JSP中提供這個Cell實現類的全路徑,但是使用Preferences更簡潔。
column.filterCell.filteredDroplist=org.extremesite.cell.FilteredDroplistCell
在ColumnTag通過設置filterCell屬性來使用FilteredDroplistCell。
<ec:column property="lastName" filterCell="filteredDroplist"/>
如果不清楚Preferences和ColumnTag定義語法請參考Preferences指南。