Active Directory - 通过指定搜索过滤器和搜索控件进行搜索,无需上下文

时间:2015-12-07 17:12:55

标签: java active-directory ldap

我按照this教程搜索了活动目录。

示例代码:

class SearchSubtree {
  public static void main(String[] args) {

    Hashtable<String, Object> env = new Hashtable<String, Object>(11);
    env
        .put(Context.INITIAL_CONTEXT_FACTORY,
            "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, "ldap://localhost:389/o=JNDITutorial");

    try {
      DirContext ctx = new InitialDirContext(env);

      String[] attrIDs = { "sn", "telephonenumber", "golfhandicap", "mail" };
      SearchControls ctls = new SearchControls();
      ctls.setReturningAttributes(attrIDs);
      ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);

      String filter = "(&(sn=Geisel)(mail=*))";

      NamingEnumeration answer = ctx.search("", filter, ctls);

      // Print the answer
      ctx.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

NameNotFoundException被抛出

NamingEnumeration answer = ctx.search("", filter, ctls);

但是当我通过"DC=extldap,DC=com"作为第一个参数时,代码工作正常。

教程有什么问题吗?第一个参数可以不是空字符串吗?或者这是Active Directory的限制吗?

1 个答案:

答案 0 :(得分:1)

一般来说,对于LDAP服务器,您始终需要根上下文才能开始搜索。基本上,您正在尝试搜索SQL数据库而不指定数据库或表名。

某些服务器实现可能允许空上下文(我知道在某些情况下iPlanet曾经允许它),但这些是规则的例外。

search(Name, String, SearchControls)的javadoc说:

  

在命名的上下文或对象中搜索满足该条目的条目   给定搜索过滤器。执行搜索指定的搜索   控制。

     

有关详细信息,请参阅DC=<your>,DC=<domain>

     

参数:

     
      
  • 命名要搜索的上下文或对象的名称
  •   
     

...

通常,在Active Directory中,可以从域根开始搜索,这始终是{{1}}。 这就是你的第二次搜索工作的原因。