Basic Search

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

以下代码创建一个属性集matchAttrs,它具有两个属性"sn""mail"。它指定符合条件的条目必须具有值为"Geisel"的姓("sn")属性和具有任何值的"mail"属性。然后,它调用DirContext.search()在上下文"ou=People"中搜索具有matchAttrs指定的属性的条目。

// Specify the attributes to match
// Ask for objects that has a surname ("sn") attribute with 
// the value "Geisel" and the "mail" attribute

// ignore attribute name case
Attributes matchAttrs = new BasicAttributes(true); 
matchAttrs.put(new BasicAttribute("sn", "Geisel"));
matchAttrs.put(new BasicAttribute("mail"));

// Search for objects that have those matching attributes
NamingEnumeration answer = ctx.search("ou=People", matchAttrs);

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

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

printAttrs\(\)the getAttributes()示例中打印属性集的代码相似。

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

# java SearchRetAll
>>>cn=Ted Geisel
attribute: sn
value: Geisel
attribute: objectclass
value: top
value: person
value: organizationalPerson
value: inetOrgPerson
attribute: jpegphoto
value: [B@1dacd78b
attribute: mail
value: [email protected]
attribute: facsimiletelephonenumber
value: +1 408 555 2329
attribute: cn
value: Ted Geisel
attribute: telephonenumber
value: +1 408 555 5252

返回所选属性

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

// Specify the ids of the attributes to return
String[] attrIDs = {"sn", "telephonenumber", "golfhandicap", "mail"};

// Search for objects that have those matching attributes
NamingEnumeration answer = ctx.search("ou=People", matchAttrs, attrIDs);

This example返回条 Object 属性"sn""telephonenumber""golfhandicap""mail",这些条目具有属性"mail"且具有"sn"属性的值"Geisel"。本示例产生以下结果。 (该条目没有"golfhandicap"属性,因此不会返回.)

# java Search 
>>>cn=Ted Geisel
attribute: sn
value: Geisel
attribute: mail
value: [email protected]
attribute: telephonenumber
value: +1 408 555 5252