LDAP分页报cookies 无效 java 怎么获取ldap cookies
LDAP分页查询是一种常见的方式,它可以使用cookie跟踪查询的状态,从而实现分页查询。但有时候,可能会遇到“cookies无效”的问题,这可能是由于cookie过期或者被清除导致的。解决这个问题的方法是重新执行LDAP查询,并重新获取cookie。
在Java中获取LDAP可以使用JNDI(Java Naming and Directory Interface)API。以下是一个使用JNDI API执行LDAP查询的示例代码:
// 创建LDAP连接
Hashtable<String, String> env = new Hashtable<>();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldap://localhost:389");
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, "cn=admin,dc=example,dc=com");
env.put(Context.SECURITY_CREDENTIALS, "password");
LdapContext ctx = new InitialLdapContext(env, null);
// 创建LDAP查询
SearchControls searchControls = new SearchControls();
searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
searchControls.setCountLimit(100); // 每页查询100条数据
searchControls.setReturningAttributes(new String[] { "cn", "mail" });
Cookie cookie = null; // 初始化cookie
do {
// 执行LDAP查询
NamingEnumeration<SearchResult> results = ctx.search("ou=people,dc=example,dc=com", "(objectClass=person)", searchControls, cookie);
while (results.hasMore()) {
SearchResult result = results.next();
Attributes attrs = result.getAttributes();
String cn = attrs.get("cn").get().toString();
String mail = attrs.get("mail").get().toString();
System.out.println(cn + ": " + mail);
}
// 获取下一页的cookie
Control[] controls = ctx.getResponseControls();
if (controls != null) {
for (Control control : controls) {
if (control instanceof PagedResultsResponseControl) {
cookie = ((PagedResultsResponseControl) control).getCookie();
}
}
}
} while (cookie != null);
// 关闭LDAP连接
ctx.close();
在上述代码中,我们首先创建了一个LDAP连接,然后使用SearchControls设置查询参数,包括查询范围、每页查询数量和返回属性等。接着,我们使用cookie跟踪查询状态,执行LDAP查询,并遍历结果集。最后,我们获取下一页的cookie,并重复执行查询,直到所有数据都被查询完毕。最后,我们关闭LDAP连接。
原文地址: https://www.cveoy.top/t/topic/bELd 著作权归作者所有。请勿转载和采集!