我查看了 Primefaces 2.2 源代码,解码数据表时将使用 DataHelper 类来解码选择。所以我复制代码来编写一个 util 类,如下所示:
//when the validator in a row, the datatable clientId will be wrong append the row number. so please specify the table clientId.
public Object getDataTableSelection(FacesContext context, DataTable table, String dataTableclientId) {
String clientId = dataTableclientId != null ? dataTableclientId : table.getClientId(context);
Map<String, String> params = context.getExternalContext().getRequestParameterMap();
String selection = params.get(clientId + "_selection");
Object data = null;
if (table.isSingleSelectionMode()) {
data = decodeSingleSelection(table, selection);
} else {
data = decodeMultipleSelection(table, selection);
}
table.setRowIndex(-1); // clean
return data;
}
private Object decodeSingleSelection(DataTable table, String selection) {
Object data = null;
if (isValueBlank(selection)) {
table.setSelection(null);
table.setEmptySelected(true);
} else {
int selectedRowIndex = Integer.parseInt(selection);
int first = table.getFirst();
int rows = table.getRows();
int last = rows == 0 ? table.getRowCount() : rows;
if (first <= selectedRowIndex && (first + last) > selectedRowIndex) {
table.setRowIndex(selectedRowIndex);
data = table.getRowData();
table.setSelection(table.getRowData());
}
}
return data;
}
private boolean isValueBlank(String value) {
if (value == null)
return true;
return value.trim().equals("");
}
private Object decodeMultipleSelection(DataTable table, String selection) {
Class<?> clazz =
table.getValueExpression("selection").getType(FacesContext.getCurrentInstance().getELContext());
Object data = null;
if (isValueBlank(selection)) {
data = Array.newInstance(clazz.getComponentType(), 0);
table.setSelection(data);
} else {
if (!table.isCellSelection()) {
String[] rowSelectValues = selection.split(",");
data = Array.newInstance(clazz.getComponentType(), rowSelectValues.length);
for (int i = 0; i < rowSelectValues.length; i++) {
table.setRowIndex(Integer.parseInt(rowSelectValues[i]));
Array.set(data, i, table.getRowData());
}
table.setSelection(data);
}
}
return data;
}
所以你可以使用该getDataTableSelection(current facescontext instance, datatable instance, table clientId)
方法来获取选择。它将返回一个数组对象(永远不会为空)。
注意:当validator在一行时,datatable的clientId会错误的追加行号。所以请指定表clientId。