afunms

My Software,My Dream—Forge a more perfect NMS product.

java ldap (1)





先用ldapbrowser测试下AD服务器,保证AD是可用的。
以下是java代码:

 

 

package com.coreware.ems;

import java.util.Hashtable;

import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.*;

public class SimpleLDAPClient {
    
public static void main(String[] args) {
        Hashtable env 
= new Hashtable();

        env.put(Context.INITIAL_CONTEXT_FACTORY,
"com.sun.jndi.ldap.LdapCtxFactory");
        env.put(Context.PROVIDER_URL, 
"ldap://192.168.80.130:389/dc=coreware,dc=com");
        env.put(Context.SECURITY_AUTHENTICATION, 
"simple");
        env.put(Context.SECURITY_PRINCIPAL, 
"cn=wangfm,cn=Users,dc=coreware,dc=com");
        env.put(Context.SECURITY_CREDENTIALS, 
"abc123!@#");
        DirContext ctx 
= null;
        NamingEnumeration results 
= null;
        
try {
            ctx 
= new InitialDirContext(env);
            SearchControls controls 
= new SearchControls();
            controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
            results 
= ctx.search("""(objectclass=person)", controls);
            
            
while (results.hasMoreElements()) {
                SearchResult searchResult 
= (SearchResult) results.next();
                Attributes attributes 
= searchResult.getAttributes();
                Attribute attr 
= attributes.get("cn");
                String cn 
= (String) attr.get();
                System.out.println(
" Person Common Name = " + cn);
            }

        }
 catch (NamingException e) {
            e.printStackTrace();
        }
 finally {
            
if (results != null{
                
try {
                    results.close();
                }
 catch (Exception e) {
                }

            }

            
if (ctx != null{
                
try {
                    ctx.close();
                }
 catch (Exception e) {
                }

            }

        }

    }

}


运行结果:
 Person Common Name = Administrator
 Person Common Name = Guest
 Person Common Name = afunms
 Person Common Name = db2admin
 Person Common Name = AFUNMS-WIN2008
 Person Common Name = krbtgt
 Person Common Name = wangfm

posted on 2012-02-23 15:38 afunms 阅读(315) 评论(0)  编辑  收藏


只有注册用户登录后才能发表评论。


网站导航:
 

My Links

News

留言簿(18)

随笔档案

相册

搜索

最新评论

阅读排行榜