// String filter = "(&(objectClass=top)(objectClass=organizationalPerson)("+ attribute +"=" + value + "))";
String filter = "(&(objectClass=top)(objectClass=organizationalUnit)("+ attribute +"=" + value + "))";
// String[] attrPersonArray = {"uid","userPassword","displayName","distinguishedName","sAMAccountName","sAMAccountType","name","cn","sn","mobile","telephoneNumber","mail","userPassword","description"};
String[] attrPersonArray = {"name","distinguishedName","whenChanged","whenCreated"};
SearchControls sc = new SearchControls();
sc.setSearchScope(SearchControls.SUBTREE_SCOPE);//SUBTREE_SCOPE三个查询范围,分别代表 当前对象查询、当前节点下对象查询、当前节点所有子目录查询
sc.setReturningAttributes(attrPersonArray);
try {
NamingEnumeration<SearchResult> sr = ctx.search(dn, filter.toString(), sc);
while(sr.hasMore()){
SearchResult result = sr.next();
NamingEnumeration<? extends Attribute> attrs = result.getAttributes().getAll();
while(attrs.hasMore()){
Attribute attr= attrs.next();
System.out.println(attr.getID() + "~~~~~~" + attr.get());
}
}
} catch (NamingException e) {
throw new UnsupportedOperationException("Unexpected Exception", e);
} finally{
//closeCtx();
}
}
上面代码查询所有的组织机构,当查询到最后一条的时候会抛出来异常信息,
Exception in thread "main" java.lang.UnsupportedOperationException: Unexpected Exception
at com.web.test.TestLDAP.search(TestLDAP.java:149)
at com.web.test.TestLDAP.main(TestLDAP.java:83)
Caused by: javax.naming.PartialResultException: Unprocessed Continuation Reference(s); remaining name ''
at com.sun.jndi.ldap.LdapCtx.processReturnCode(Unknown Source)
at com.sun.jndi.ldap.LdapCtx.processReturnCode(Unknown Source)
at com.sun.jndi.ldap.LdapNamingEnumeration.getNextBatch(Unknown Source)
at com.sun.jndi.ldap.LdapNamingEnumeration.hasMoreImpl(Unknown Source)
at com.sun.jndi.ldap.LdapNamingEnumeration.hasMore(Unknown Source)
at com.web.test.TestLDAP.search(TestLDAP.java:139)
... 1 more
经过查询资料,发现方法hasMore的问题,修改为如下就没有问题了,
while(sr.hasMoreElements()){
SearchResult result = sr.next();
NamingEnumeration<? extends Attribute> attrs = result.getAttributes().getAll();
while(attrs.hasMore()){
Attribute attr= attrs.next();
System.out.println(attr.getID() + "~~~~~~" + attr.get());
}
}
参考资料:
http://forum.spring.io/forum/spring-projects/data/ldap/68622-retrieve-user-via-filter
参考内容:
NamingEnumeration.hasMore()
The JavaDoc for NamingEnumeration describes how hasMore() should function:
* When the last of the results has been returned by the NamingEnumeration's
* next(), invoking hasMore() would result in PartialResultException being thrown.
In the Template, there are several methods that call hasMore() when it appears they should be calling hasMoreElements() instead.
hasMoreElements() does not throw the error and instead returns the expected true or false
本文介绍了一个关于LDAP查询中出现的异常问题及解决方案。通过对比hasMore()与hasMoreElements()方法,解决了在查询最后一条记录时抛出的PartialResultException异常。
2295

被折叠的 条评论
为什么被折叠?



