我設法讓分頁工作像描述的here一樣工作。問題是我需要公開一個看起來像這樣的API:getUsers(pageSize, pageNumber)
,這對於JNDI/LDAP執行分頁的方式(每次傳遞給搜索方法的cookie)都不太合適。代碼如下所示:JNDI-LDAP分頁
private NamingEnumeration ldapPagedSearch(String filter, int pageSize, int pageNumber){
InitialLdapContext ctx = getInitialContext();
//TODO: get the id also, need to spec it in UI
// Create the search controls
SearchControls searchCtls = new SearchControls();
searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
//keep a session
byte[] cookie = null;
//Request the paged results control
Control[] ctls = new Control[]{new PagedResultsControl(pageSize, true)};
ctx.setRequestControls(ctls);
//Specify the search scope
NamingEnumeration results = null;
int currentPage = 1;
do {
results = ctx.search(getConfiguration().get(BASEDN_KEY), filter, searchCtls);
//we got to the right page, return this page
if(currentPage == pageNumber) {
return results;
}
// loop through this page, because we cannot get a proper cookie otherwise
// WARN: this could be a problem of performance
while (results.hasMore()) results.next();
// examine the paged results control response
Control[] controls = ctx.getResponseControls();
if (controls != null) {
for (Control control : controls) {
if (control instanceof PagedResultsResponseControl) {
cookie = ((PagedResultsResponseControl) control).getCookie();
}
}
}
// pass the cookie back to the server for the next page
ctx.setRequestControls(new Control[]{new PagedResultsControl(pageSize, cookie, Control.CRITICAL) });
//increment page
currentPage++;
} while (cookie != null);
ctx.close();
//if we get here, means it is an empty set(consumed by the inner loop)
return results;
}
看來我需要遍歷所有頁面以獲取所需的頁面。此外,我需要遍歷頁面上的所有條目,以便能夠獲取下一頁。
有沒有更好的方法?我擔心性能問題。