📄 searchldap.java
字号:
/*曾海 2003/9 JNDI搜索程序连接后进行模式搜索,显示查到的有关记录的所有信息。显示的内容比较多。*/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://127.0.0.1:50028";//别用localhost ,有时候不对劲 public static String searchBase= "dc=jssvc, dc=com";//从默认的点开始寻找,这里的根是dc-dc public static String searchContents="(uid=*)";//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 扫描某个用户的属性表 }//外层扫描多条用户记录的循环 }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 + -