技术开发 频道

目录服务与JNDI


IT168技术文档】 
    搜索并显示有限的属性 
    显示属性必然是显示某条记录的属性。在上例中,取属性集合的语句是 
    Attributes attrs = sr.getAttributes() ; 
    其中 sr 是 Searchresult 类型,代表某条记录,getAttributes 取出它的所有属性。 
    如果要取部分属性,就不用 SearchResult 的 getAttributes 方法,而是用Attributes attrs=ctx.getAttributes(dn,attrArray) ;
这个 getAttributes 方法是 ctx 的。带两个参数: 
    第一个参数 dn,表明你到底要显示哪条记录的属性。一个 dn 唯一地标识了一条记录。 
    用 SearchResult 的 getName 可以取得这条记录的 dn。getName 取得的是相对 dn,相当于文件目录中的相对路径。如果要用绝对路径,可以加上 searchBase 获得全路径。 
    如果你愿意,直接写 dn 串也可以。 
    第二个参数是 attrArray,这是一个字符串数组,每个元素都是一个属性名: 
    String attrArray[]={ “sn”,”street”} 
    就指明,我要取 sn 和 street 两个属性。 
    取得 Attrs 后,它也是个属性集,里面有多个属性,本例中就是 sn 和 Street。每个属性有多个值,所以还要用一循环取属性值:
for(int k=0;k< attrArray.length ;k++){ Attribute item = (Attribute) attrs.get(attrArray[k]);
    属性值集合取到 Attribute 对象中,方法是 get(属性名)。取到之后,Attribute item 当然是一个集合,用循环显示它就得到全部属性值。
程序的代码如下:
Hashtable env = new Hashtable(11); env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, "ldap://localhost:389"); env.put(Context.SECURITY_AUTHENTICATION, "simple"); env.put(Context.SECURITY_PRINCIPAL, "cn=Manager,o=JNDITutorial"); env.put(Context.SECURITY_CREDENTIALS, "secret"); String searchBase= "ou=Groups,o=JNDITutorial";//从默认的点开始寻找,这里的根是 dc-dc String searchContents="(cn=*)"; try { /* get a handle to an Initial DirContext */ DirContext ctx = new InitialDirContext(env); /* specify search constraints to search subtree */ SearchControls constraints = new SearchControls(); constraints.setSearchScope(SearchControls.SUBTREE_SCOPE); /* search for all entries with surname of Jensen */ NamingEnumeration results = ctx.search(searchBase, searchContents, constraints); String attrArray[]={ "ou","cn"}; Enumeration enu; /* for each entry print out name + all attrs and values */ while (results != null && results.hasMore()) { SearchResult si = (SearchResult)results.next(); String dn=si.getName() ; dn+=" , "+searchBase; System.err.println("找到的记录标记是: "+dn ); Attributes attrs=ctx.getAttributes(dn,attrArray) ;//在 imail 里无法正确运行 if (attrs==null){ System.err.println("字段不存在"); } else{ for(int k=0;k< attrArray.length ;k++){ Attribute item = (Attribute) attrs.get(attrArray[k]); System.err.println("属性名:"+attrArray[k]+"的值集是"); enu = item.getAll() ; while(enu!=null && enu.hasMoreElements() ) System.err.print(enu.nextElement()+" ** " ); System.err.println() ; } } System.out.println(); } } catch (NamingException e) { System.err.println("Search example failed."); e.printStackTrace(); }
0
相关文章