如何使用Java操作LDAP之檢索條目(二)
本篇文章為大家介紹一下如何在LDAP下檢索條目,你可以把這個操作想象成查詢資料庫裡的記錄。由於LDAP的資料儲存是一個樹形結構,所以一般的檢索都是為了檢索出某個條目有哪些下級條目。
1、為了程式更健壯,我先給出一個判斷條目是否存在的函式:
//判斷條目是否已存在
static public boolean IsExist(String ldappath)
{
DirContext ctx = null; //這是LDAP的連線物件,上篇文章中已經介紹過
ctx = GetConnection(); //GetConnection其實就是用上篇文章中的程式碼所寫的一個函式
{
ctx.search(ldappath, null); //測試檢索一下
return true; //表示這個條目是存在的
}
catch(NamingException ex)
{
return false;
}
}
2、檢索某條目的下級條目
//檢索條目的下級條目
//ldappath 本級條目路徑,如:dc=cs,dc=hunan,dc=com
//attrname 用於過濾的屬性名,即條目包含該屬性,可為空串
//attrval 用於過濾的屬性值,即上面的屬性包含該屬性值,可為空串
//注意,當attrname為空串時,將忽略attrval
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