基本搜索

原文: https://docs.oracle.com/javase/tutorial/jndi/ops/basicsearch.html

最简单的搜索形式要求您指定条目必须具有的属性集以及执行搜索的目标上下文的名称。

以下代码创建了一个属性集matchAttrs ,它有两个属性“sn”“mail”。它指定合格条目必须具有姓氏(“sn”)属性,其值为“Geisel”“邮件”属性,具有任何值。然后调用 DirContext.search() 搜索上下文“ou = People”,查找具有matchAttrs指定属性的条目。

  1. // Specify the attributes to match
  2. // Ask for objects that has a surname ("sn") attribute with
  3. // the value "Geisel" and the "mail" attribute
  4. // ignore attribute name case
  5. Attributes matchAttrs = new BasicAttributes(true);
  6. matchAttrs.put(new BasicAttribute("sn", "Geisel"));
  7. matchAttrs.put(new BasicAttribute("mail"));
  8. // Search for objects that have those matching attributes
  9. NamingEnumeration answer = ctx.search("ou=People", matchAttrs);

然后,您可以按如下方式打印结果。

  1. while (answer.hasMore()) {
  2. SearchResult sr = (SearchResult)answer.next();
  3. System.out.println(">>>" + sr.getName());
  4. printAttrs(sr.getAttributes());
  5. }

printAttrs()类似于 打印属性集的示例。

运行 this example 会产生以下结果。

  1. # java SearchRetAll
  2. >>>cn=Ted Geisel
  3. attribute: sn
  4. value: Geisel
  5. attribute: objectclass
  6. value: top
  7. value: person
  8. value: organizationalPerson
  9. value: inetOrgPerson
  10. attribute: jpegphoto
  11. value: [B@1dacd78b
  12. attribute: mail
  13. value: Ted.Geisel@JNDITutorial.example.com
  14. attribute: facsimiletelephonenumber
  15. value: +1 408 555 2329
  16. attribute: cn
  17. value: Ted Geisel
  18. attribute: telephonenumber
  19. value: +1 408 555 5252

上一个示例返回了与满足指定查询的条目关联的所有属性。您可以通过传递search()要包含在结果中的属性标识符数组来选择要返回的属性。在创建matchAttrs之后,如前所示,您还需要创建属性标识符数组,如下所示。

  1. // Specify the ids of the attributes to return
  2. String[] attrIDs = {"sn", "telephonenumber", "golfhandicap", "mail"};
  3. // Search for objects that have those matching attributes
  4. NamingEnumeration answer = ctx.search("ou=People", matchAttrs, attrIDs);

This example 返回属性“sn”“telephonenumber”“golfhandicap”“mail”[具有属性“mail”且具有“sn”属性且具有值“Geisel”的条目的 HTG9]。此示例生成以下结果。 (该条目没有“golfhandicap”属性,因此不会返回。)

  1. # java Search
  2. >>>cn=Ted Geisel
  3. attribute: sn
  4. value: Geisel
  5. attribute: mail
  6. value: Ted.Geisel@JNDITutorial.example.com
  7. attribute: telephonenumber
  8. value: +1 408 555 5252