?? jndiauth.java
字號:
//package jndi;/*曾海 2003/9 JNDI搜索程序驗證連接系統。*/import java.util.*;// hashtableimport javax.naming.*;//命名服務import javax.naming.directory.*;//初始化上下文用import javax.swing.JOptionPane;/* ldap的端口是389,ldap://localhost:389 如果是sunone用戶,連接50028口子。之前別忘記先開用戶,挺復雜的,看我的教程吧。 準備驗證地連接上服務器在服務上準備:uid=ZHai,ou=Groups,dc=jssvc,dc=com記錄。密碼設成916,如果不會請看講義*/public class JNDIAuth { public static String sunLdapContext="com.sun.jndi.ldap.LdapCtxFactory"; public static String hostURL="ldap://127.0.0.1:389";//這個端口取決于你安裝時的選擇。 public static String searchBase= "obj=user,cn=portal";//從默認的點開始尋找,這里的根是dc-dc public static String searchContents="(uid=*)";//sn=surname名字(sn=zeng)也可以,大家可以試試sn=*可以任意匹配 public static String dn="cn=portal"; public static String pw="secret"; public JNDIAuth() { pw = JOptionPane.showInputDialog(null,null,"輸入您的密碼啦!",JOptionPane.DEFAULT_OPTION ); try{ Hashtable env = new Hashtable();//準備放屬性 env.put(Context.INITIAL_CONTEXT_FACTORY ,sunLdapContext); env.put(Context.PROVIDER_URL ,hostURL); env.put(Context.SECURITY_AUTHENTICATION ,"simple"); env.put(Context.SECURITY_PRINCIPAL ,dn); env.put(Context.SECURITY_CREDENTIALS,pw); SearchControls constraints = new SearchControls();//這個類在naming.directory里的,用于確定搜索的范圍,是全局,一層還是下一層,請看我的備課筆記 constraints.setSearchScope(SearchControls.SUBTREE_SCOPE ) ;//搜索全部的目錄樹 DirContext ctx = new InitialDirContext(env);//這句會有意外,好好捉吧 System.err.println("非常好,連接上了"); 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) { JNDIAuth JNDIAuth1 = new JNDIAuth(); System.exit(0); }}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -