列的filterCell屬性控制過(guò)濾器如何顯示,它和cell屬性非常相像并且也是實(shí)現(xiàn)Cell接口。馬上要定義的是默認(rèn)的和droplist這兩個(gè)過(guò)濾器cells。
默認(rèn)的是一個(gè)輸入框元素而droplist是一個(gè)下拉列表元素。當(dāng)然,如果你需要進(jìn)行一些定制你可以插接自己的實(shí)現(xiàn)。
最近,我被問(wèn)到是否能夠?qū)崿F(xiàn)一個(gè)過(guò)濾器cell,顯示已經(jīng)通過(guò)別的過(guò)濾器過(guò)濾得到數(shù)據(jù)子集。答案當(dāng)然是肯定的,而且這是我將在這里示范的。通常定制的
cell可以很容易被創(chuàng)建,這個(gè)示例將印證這點(diǎn)。在這個(gè)示例里last name列里顯示的將是通過(guò)first name過(guò)濾后的子集。如果沒(méi)有通過(guò) first
name過(guò)濾那么所有值都將被顯示。
1.1. 定制Droplist過(guò)濾器Cell示例
通常你只需要為過(guò)濾器cell實(shí)現(xiàn)Cell接口。然而,因?yàn)槲覀円獎(jiǎng)?chuàng)建的過(guò)濾器cell是一個(gè)下拉列表,我們可以通過(guò)擴(kuò)展
FilterDroplistCell來(lái)獲得它已經(jīng)提供的很多功能,F(xiàn)ilterDroplistCell是發(fā)行包已經(jīng)提供的cells之一。
我們需要覆蓋FilterDroplistCell的唯一方法是getFilterDropList()。這是整個(gè)類的全部代碼:
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;
}
}
如果你比較這個(gè)類和父類,你會(huì)發(fā)現(xiàn)它們只有微小的區(qū)別。
首先需要注意的是我們需要找出first name是否已經(jīng)被過(guò)濾了。
String firstNameFilter = model.getLimit().getFilterSet().getValue("firstName");
然后我們需要判斷當(dāng)前bean的first name值是否和first name過(guò)濾器值相同。如果相同,將當(dāng)前的last name值
添加到droplist中。
String firstName = BeanUtils.getProperty(bean, "firstName");
if (StringUtils.isNotBlank(firstNameFilter) && !firstName.equals(firstNameFilter)) {
continue;
}
如果last name將添加到droplist中,我們需要檢查droplist中是否已經(jīng)包含了這個(gè)值。如果沒(méi)有,我們就把它添加到droplist中。
String lastName = BeanUtils.getProperty(bean, column.getProperty());
if ((lastName != null) && !droplist.contains(lastName)) {
droplist.add(lastName);
}
為了使用這個(gè)Cell你應(yīng)該在Preferences中聲明一個(gè)別名。 當(dāng)然,你可以省略這步而在JSP中提供這個(gè)Cell實(shí)現(xiàn)類的全路徑,但是使用Preferences更簡(jiǎn)潔。
column.filterCell.filteredDroplist=org.extremesite.cell.FilteredDroplistCell
在ColumnTag通過(guò)設(shè)置filterCell屬性來(lái)使用FilteredDroplistCell。
<ec:column property="lastName" filterCell="filteredDroplist"/>
如果不清楚Preferences和ColumnTag定義語(yǔ)法請(qǐng)參考Preferences指南。