文档

Java™ 教程
隐藏目录
基本搜索
路径: Java命名和目录接口
教程: 命名和目录操作
章节: 搜索

基本搜索

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

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

// 指定要匹配的属性
// 要求具有姓氏("sn")属性值为"Geisel"和"mail"属性

// 忽略属性名称大小写
Attributes matchAttrs = new BasicAttributes(true); 
matchAttrs.put(new BasicAttribute("sn", "Geisel"));
matchAttrs.put(new BasicAttribute("mail"));

// 搜索具有这些匹配属性的对象
NamingEnumeration answer = ctx.search("ou=People", matchAttrs);

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

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

printAttrs()类似于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: Ted.Geisel@JNDITutorial.example.com
attribute: facsimiletelephonenumber
value: +1 408 555 2329
attribute: cn
value: Ted Geisel
attribute: telephonenumber
value: +1 408 555 5252

返回所选属性

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

// 指定要返回的属性的标识符
String[] attrIDs = {"sn", "telephonenumber", "golfhandicap", "mail"};

// 搜索具有这些匹配属性的对象
NamingEnumeration answer = ctx.search("ou=People", matchAttrs, attrIDs);

这个例子 返回具有属性 "sn""telephonenumber""golfhandicap""mail" 的条目,这些条目具有一个属性 "mail" 并且具有一个值为 "Geisel""sn" 属性。这个例子产生以下结果。(条目没有 "golfhandicap" 属性,因此不会返回。)

# java Search 
>>>cn=Ted Geisel
属性:sn
值:Geisel
属性:mail
值:Ted.Geisel@JNDITutorial.example.com
属性:telephonenumber
值:+1 408 555 5252

上一页: 搜索
下一页: 过滤器