蜜x蜜水果糖 漫画类似:使用JNDI操作LDAP(3)
来源:百度文库 编辑:中财网 时间:2024/05/09 12:01:56
l 读取属性
当读取目录中一个对象的属性时,需要将对象名传给LdapContext.getAttributes()方法作参数。假设有一个名为”cn=Ted Geisel,ou=people”的对象,为了获取它的属性,需要使用如下的代码:
Attributes answer = ctx.getAttributes("cn=Ted Geisel, ou=People");
通过下面的代码迭代打出所有的属性名和属性值:
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()));
}
执行的结果如下:
attribute: telephonenumber
value: +1 408 555 5252
attribute: mail
value: Ted.Geisel@JNDITutorial.com
attribute: facsimiletelephonenumber
value: +1 408 555 2329
返回指定的属性:
为了运行所有属性的一个子集,可以指定一个属性名数组来指定需要获取的属性:
// Specify the ids of the attributes to return
String[] attrIDs = { "sn", "telephonenumber", "golfhandicap",
"mail" };
// Get the attributes requested
Attributes answer = ctx.getAttributes("cn=Ted Geisel, ou=People",
attrIDs);
返回结果如下:
attribute: telephonenumber
value: +1 408 555 5252
attribute: mail
value: Ted.Geisel@JNDITutorial.com
attribute: sn
value: Geisel
由于这个对象没有golfhanicap属性,所以只返回三个属性。
基本检索
这是目录检索的最简单的形式,只需要指定检索结果必须包含的属性以及检索的目的上下文。下面的代码创建了一个属性集matchAttrs,其中包含两个属性,telephonenumber和mail,检索指定了实体必须具有的surname(sn)属性和mail属性,并且surname属性的值为”Geisel”,而mail的属性值任意。然后调用DirContext.search()方法在ou=people的上下文中检索符合matchAttrs的实体。
Attributes matchAttrs = new BasicAttributes(true); // ignore case
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());
GetattrsAll.printAttrs(sr.getAttributes());
}
返回结果为:
>>>cn=Ted Geisel
attribute: telephonenumber
value: +1 408 555 5252
attribute: mail
value: Ted.Geisel@JNDITutorial.com
attribute: facsimiletelephonenumber
value: +1 408 555 2329
attribute: objectClass
value: person
value: inetOrgPerson
value: organizationalPerson
value: top
attribute: jpegphoto
value: [B@179c285
attribute: sn
value: Geisel
attribute: cn
value: Ted Geisel
可以选择返回指定的属性,代码如下:
// Specify the ids of the attributes to return
String[] attrIDs = { "sn", "telephonenumber", "golfhandicap","mail" };
answer = ctx.search("ou=People", matchAttrs, attrIDs);
此时返回的结果为:
>>>cn=Ted Geisel
attribute: telephonenumber
value: +1 408 555 5252
attribute: mail
value: Ted.Geisel@JNDITutorial.com
attribute: sn
value: Geisel