JAVA登陆Window Server Active Directory并搜索用户信息以及组信息(一)

14年前

public class ADUtillong {

    private String logonName = "admin";//登陆用户名

    private String logonPassWord = "admin_123_admin";//登陆用户名相对应的密码

    private String adServerIp = "192.168.0.160";//AD服务器IP地址

    private String adServerPort ="389";//AD服务器访问端口

    private String adRoot = "dc=sol,dc=shuion,dc=com,dc=cn";//ADroot

    private  DirContext  dirContext;

    public volatile static ADUtillong utillong = null;

    public ADUtillong(){

       this.dirContext = this.createConnection();

    }

    //得到连接实例

    public static synchronized  ADUtillong getInstance(){

       if(utillong == null){

           utillong = new ADUtillong();

       }

       return utillong;

    }

    /*

     * 创建连接

     */

    private synchronized  DirContext createConnection(){

       Hashtable env = new Hashtable();

        env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");

        env.put(Context.PROVIDER_URL, "ldap://"+adServerIp+":"+adServerPort+"/");

        env.put(Context.SECURITY_AUTHENTICATION, "simple");

        env.put(Context.SECURITY_PRINCIPAL, "cn="+logonName+"," + "ou=it,ou=shanghai" + adRoot);//登陆用户名和域名

        env.put(Context.SECURITY_CREDENTIALS, logonPassWord);//密码

        try {

            this.dirContext = new InitialDirContext(env);//初始化上下文

            System.out.println("认证成功");//这里可以改成异常抛出。

        } catch (javax.naming.AuthenticationException e) {

            System.out.println("认证失败");

        } catch (Exception e) {

            System.out.println("认证出错:" + e);

        }

        return this.dirContext;

    }

   

    /*

     * 搜索

     */

    public synchronized NamingEnumeration search(String filter) throws NamingException{

       if(!isConn()){

           this.reConn();

       }

       SearchControls searchControls = new SearchControls();

       searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);// 搜索以命名对象为根的整个子树。

       return this.dirContext.search(adRoot, filter,searchControls);

    }

    /*

     * 搜索

     */

    public synchronized NamingEnumeration search(String base,String filter) throws NamingException{

       if(!base.toLowerCase().endsWith(adRoot.toLowerCase())){

           base = base + "," + adRoot;

       }

       SearchControls searchControls = new SearchControls();

       searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);// 搜索以命名对象为根的整个子树。

       return this.dirContext.search(base, filter,searchControls);

    }

   

    /*

     * 判断是否连接

     */

    public boolean isConn() throws NamingException{

       SearchControls searchControls = new SearchControls();

       NamingEnumeration answer = this.dirContext.search( adRoot,"(objectclass={0})", new Object[]{"top".getBytes()},searchControls); 

       boolean flag = answer.hasMore();

        return flag;

    }