我正试图从namingenumeration中获取元素。 namingenumeration本身不是null,但hasNext()给我假。
我做错了什么?
public static void main(String[] args) {
try {
DirContext context = new InitialDirContext(
Environment.getEnvironment());
SearchControls controls = new SearchControls();
controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
String[] attrIDs = { "cn", "givenname", "sn", "mail" };
controls.setReturningAttributes(attrIDs);
NamingEnumeration enumResult = context.search(
"DC=PORTAL,DC=COMPANY,DC=BE", "(CN=*)",
controls);
System.out.println(enumResult.hasMore());
context.close();
} catch (AuthenticationException e) {
System.out.println("Invalid credentials");
} catch (NamingException e) {
System.out.println("Lookup failed: " + e);
}
}
AD的结构(使用AD-LDS在Localhost上)
DC =门户网站,DC = COMPANY,DC = BE
- > OU =帐户
==> CN = John Doe
==> CN = Jane Doe
- > CN = LostAndFound
- > CN = NTDS配额
- > CN =角色
- > OU =系统帐户
==> CN = PortalAdmin
将我的搜索库缩小为“OU = ACCOUNTS,DC = PORTAL,DC = COMPANY,DC = BE”会出现以下错误
查找失败:javax.naming.NameNotFoundException:[LDAP:错误代码 32 - 000020 8D:NameErr:DSID-031522C9,问题2001(NO_OBJECT),数据 0,最佳匹配:'DC = PORTAL,DC = COMPANY,DC = BE'];剩余名称'OU = ACCOUNTS,DC = PORTAL,DC = COMPANY,DC = BE'
溶液:
try {
DirContext ctx = new InitialDirContext(Environment.getEnvironment());
// Get all the attributes of named object
Attributes attrs = ctx
.getAttributes("cn=John Doe,ou=Accounts,DC=PORTAL,DC=COMPANY,DC=BE");
if (attrs == null) {
System.out.println("No attributes");
} else {
/* Print each attribute */
try {
for (NamingEnumeration ae = attrs.getAll(); ae.hasMore();) {
Attribute attr = (Attribute) ae.next();
System.out.println("attribute: " + attr.getID());
/* print each value */
for (NamingEnumeration e = attr.getAll(); e.hasMore(); System.out
.println("value: " + e.next()))
;
}
} catch (NamingException e) {
e.printStackTrace();
}
}
ctx.close();
} catch (AuthenticationException e) {
System.out.println("Invalid credentials");
} catch (NamingException e) {
System.out.println("Lookup failed: " + e);
}
答案 0 :(得分:1)
从做一些基本的健全性检查开始。例如,Environment.getEnvironment()
返回的数据是正确的(url,端口,用户,密码),并允许连接到目录服务器。还要检查是否存在网络问题,并且您实际上可以访问服务器。
尝试稍微限制搜索基础,例如:“OU = Accounts,DC = PORTAL,DC = COMPANY,DC = BE”并查看是否返回了一些结果。还要检查预期结果中的对象是否实际具有属性“cn”,“givenname”,“sn”,“mail”。
除此之外,问题中显示的代码没有明显的错误,应该正常工作。