如何使用Java操作LDAP之检索条目(二)

来源:互联网 发布:重庆大学电费网络缴费 编辑:程序博客网 时间:2024/06/07 13:49

本篇文章为大家介绍一下如何在LDAP下检索条目,你可以把这个操作想象成查询数据库里的记录。由于LDAP的数据存储是一个树形结构,所以一般的检索都是为了检索出某个条目有哪些下级条目。

 

1、为了程序更健壮,我先给出一个判断条目是否存在的函数:
//判断条目是否已存在
static public boolean IsExist(String ldappath)
{
   DirContext ctx = null;          //这是LDAP的连接对象,上篇文章中已经介绍过
   ctx = GetConnection();     //GetConnection其实就是用上篇文章中的代码所写的一个函数
   try
   {
    ctx.search(ldappath, null);   //测试检索一下
    return true;                          //表示这个条目是存在的
   }
   catch(NamingException ex)
   {
         return false;    
 
}

2、检索某条目的下级条目

//检索条目的下级条目
//ldappath 本级条目路径,如:dc=cs,dc=hunan,dc=com
//attrname 用于过滤的属性名,即条目包含该属性,可为空串
//attrval     用于过滤的属性值,即上面的属性包含该属性值,可为空串
//注意,当attrname为空串时,将忽略attrval
//这个函数会返回NamingEnumeration对象,通过这个对象,我们可以遍历出所有搜索到的结果
static public NamingEnumeration<Object> SearchSubEntry(String ldappath,String attrname,String attrval)
{
   NamingEnumeration ret = null;   
   DirContext ctx = null;
   ctx = GetConnection();    //取连接对象
   if(ctx != null)
   {  
    try
    {
     if(IsExist(ldappath)) //先判断一下这个条目是不是存在
     {
      //设定搜索条件     
      Attributes matchAttrs = new BasicAttributes(true);    //建一个属性集合对象
      if(attrname.compareTo("") != 0)                       //如果传入了属性名称条件就加到属性集合里
             matchAttrs.put(new BasicAttribute(attrname, attrval));
      //搜索符合条件的结果
      NamingEnumeration answer = ctx.search(ldappath, matchAttrs);
      ret = answer;
     }
    }
    catch(NamingException ex)
      {
       ret = null;    //出现异常时会返回null
         ex.printStackTrace();
      }    
   }
   return ret;    
}

3、将上面函数的返回对象转成一个ArrayList,这样感觉更好使用,如下:

ArrayList<String> mylist= new ArrayList<String>();
NamingEnumeration<Object> sret = null;  
sret = SearchSubEntry("dc=cs,dc=hunan,dc=com","","");
while (sret.hasMore())
{
      SearchResult sr = (SearchResult) sret.next();
      mylist.add(sr.getName());
}

这样,得到的mylist就是一个包含检索结果的字符串集合,每一项就是一个子条目的名称。


转载自:http://blog.sina.com.cn/s/blog_4da69d9a0100ja76.html