?? searchldap.java
字號:
/*曾海 2003/9?。剩危模伤阉鞒绦?/span>連接后進行模式搜索,顯示查到的有關記錄的所有信息。顯示的內容比較多。*///package jndi;import java.util.*;// hashtableimport javax.naming.*;//命名服務import javax.naming.directory.*;//初始化上下文用/* ldap的端口是389,ldap://localhost:389 如果是sunone用戶,連接50028口子。之前別忘記先開用戶,挺復雜的,看我的教程吧。本程序的名字系統結構是第一層 我的domainName就是我的主機,ddn-00887第二層 我的用戶名是clyde/mirthrandir等第三層 cn就是全名組織全部是SVC*/public class SearchLDAP { /*如果你找不到相應的類名,就用Search-Search Classes來找,不會有錯了*/ public static String sunLdapContext="com.sun.jndi.ldap.LdapCtxFactory"; public static String hostURL="ldap://192.168.2.46:389";//別用localhost ,有時候不對勁 public static String searchBase= "o=ga,c=cn";//從默認的點開始尋找,這里的根是dc-dc public static String searchContents="(policeID=*)";//sn=surname名字(sn=zeng)也可以,大家可以試試sn=*可以任意匹配 public SearchLDAP() { try{ Hashtable env = new Hashtable();//準備放屬性 env.put(Context.INITIAL_CONTEXT_FACTORY ,sunLdapContext); env.put(Context.PROVIDER_URL ,hostURL); SearchControls constraints = new SearchControls();//這個類在naming.directory里的,用于確定搜索的范圍,是全局,一層還是下一層,請看我的備課筆記 constraints.setSearchScope(SearchControls.SUBTREE_SCOPE ) ;//搜索全部的目錄樹 DirContext ctx = new InitialDirContext(env);//這句會有意外,好好捉吧 System.err.println("非常好,連接上了"); //搜索的結果是個Naming Enumeration集合對象,代表所有查到的用戶 // 這個集合對象里有的是單個的SearchResult對象,一個對象一個用戶 //SearchResulut里面包括一個 dn 和一個 Attributes對象集合 //Attributes集合里每個元素是一個Attributes對象,代表一張用戶信息表 //每個Attributes對象里是一堆的NamingEumeration,用getAll取得,針對用戶的一行信息 //一個attributes對象里是一個enumeration,內容是某一項比如mail的多個值,頭昏了吧。哈哈 NamingEnumeration results = ctx.search(searchBase,searchContents,constraints); while(results!=null && results.hasMore() ){ SearchResult sr =(SearchResult) results.next() ; System.err.println("找到的記錄標記是"+sr.getName() ); Attributes attrs = sr.getAttributes() ;//來自javax.naming.directory,某條記錄的屬性,一張表 NamingEnumeration ne = attrs.getAll() ;//取出這張表,一行就是一個Attribute while( ne!=null && ne.hasMoreElements() ){ Attribute attr =(Attribute) ne.next() ; System.err.print(attr.getID() +"內容是");//每個行,比如mail地址,可能有多條,痛苦吧 Enumeration details = attr.getAll() ; while(details!=null && details.hasMoreElements() ){ System.err.println(" --- "+details.nextElement() ); }//處理某一項,如mail,的多個值 }//內部while 掃描某個用戶的屬性表 System.out.println("========================================"); }//外層掃描多條用戶記錄的循環 }catch (Exception e){ System.err.println("錯誤,連接不上服務器") ; System.exit(1);}; } public static void main(String[] args) { SearchLDAP SearchLDAP1 = new SearchLDAP(); System.exit(0); }}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -