我设法让分页工作像描述的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;
}
看来我需要遍历所有页面以获取所需的页面。此外,我需要遍历页面上的所有条目,以便能够获取下一页。
有没有更好的方法?我担心性能问题。