Java操作ldap的基本方法(上)(增删改查),针对初学者,非常实用!

前段时间,领导提了一个需求:利用java代码让mysql和ldap的数据做到动态同步。听完之后赶紧去百度,什么是ldap、ldap如何安装、ldap环境搭建方法.......这些基本的步骤网上有很多文章,都没什么大问题,我建议大家要了解清楚ldap的基本属性,能在ldap工具进行一些基本的部门、用户的操作。

一切准备就绪之后,我想第一步就是先连接上ldap吧,这一步也没什么大问题,我就不贴代码了,分享一个博客,没有连接成功的可以进去看一下https://blog.csdn.net/kkdelta/article/details/40540255

OK,我们已经完成了最基本的操作,接下来我想先不管mysql,利用java做一些简单的ldap增删改查测试,我的原则就是先学会爬再学走。话不多说哈,我们赶快开始吧!

先说一下我使用到的一些工具:Intellij IDEA、Ldap Admin Tool(ApacheDirectoryStudio)、Navicat Lite。我创建的是maven项目,需要添加一个jar包,别的jar包都是基于java的。如果你也是maven项目需要添加如下依赖。如果不是的话你可以下载jar包放进项目

<!-- https://mvnrepository.com/artifact/com.novell.ldap/jldap -->
<dependency>
    <groupId>com.novell.ldap</groupId>
    <artifactId>jldap</artifactId>
    <version>2009-10-07</version>
</dependency>

附上一张Ldap Admin Tool的图片,说实话我对这玩意还是似懂非懂,如果看到这篇博客有对ldap熟悉的话欢迎评论里留下联系方式,我请教一些问题(/奸笑脸)

我们先将ldap里我瞎JB添加的一些用户信息查询出来吧,下面是java代码:

package com.spring.ldap;

import com.novell.ldap.*;
import com.novell.ldap.LDAPConnection;
import com.novell.ldap.LDAPSearchResults;
import com.novell.ldap.util.Base64;

import java.io.UnsupportedEncodingException;
import java.util.Enumeration;
import java.util.Iterator;

/**
 * @author jiannnig
 * @description 查询条目示例
 * @date 2018/11/8
 * @time 15:13
 */
public class LDAPSearchDemo {

    public static void main(String[] args) {
        //根据自己情况更改
        String ldapHost = "localhost";
        String loginDN = "cn=Manager,dc=maxcrc,dc=com";
        String password = "secret";
        String searchBase = "dc=maxcrc,dc=com";
        String searchFilter = "objectClass=*";
        int ldapPort = LDAPConnection.DEFAULT_PORT;
        // 查询范围
        // SCOPE_BASE、SCOPE_ONE、SCOPE_SUB、SCOPE_SUBORDINATESUBTREE
        int searchScope = LDAPConnection.SCOPE_SUB;
        LDAPConnection lc = new LDAPConnection();
        try {
            lc.connect(ldapHost, ldapPort);
            lc.bind(LDAPConnection.LDAP_V3, loginDN, password.getBytes("UTF8"));
            LDAPSearchResults searchResults = lc.search(searchBase,searchScope, searchFilter, null, false);
            while (searchResults.hasMore()) {
                LDAPEntry nextEntry = null;
                try {
                    nextEntry = searchResults.next();

                }catch (LDAPException e) {
                    System.out.println("Error: " + e.toString());
                    if (e.getResultCode() == LDAPException.LDAP_TIMEOUT|| e.getResultCode() == LDAPException.CONNECT_ERROR) {
                        break;
                    }else {
                        continue;
                    }
                }
                System.out.println("DN =: " + nextEntry.getDN());
                System.out.println("|---- Attributes list: ");
                LDAPAttributeSet attributeSet = nextEntry.getAttributeSet();
                Iterator<LDAPAttribute> allAttributes = attributeSet.iterator();
                while (allAttributes.hasNext()) {
                    LDAPAttribute attribute = allAttributes.next();
                    String attributeName = attribute.getName();
                    Enumeration<String> allValues = attribute.getStringValues();
                    if (null == allValues) {
                        continue;
                    }
                    while (allValues.hasMoreElements()) {
                        String value = allValues.nextElement();
                        if (!Base64.isLDIFSafe(value)) {
                            // base64 encode and then print out
                            value = Base64.encode(value.getBytes());

                        }
                        System.out.println("|---- ---- " + attributeName+ " = " + value);
                    }
                }
            }


        }catch (LDAPException e) {
            System.out.println("Error: " + e.toString());
        } catch (UnsupportedEncodingException e) {
            System.out.println("Error: " + e.toString());
        }finally {
            try {
                if (lc.isConnected()) {
                    lc.disconnect();
                }
            }catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

右键Run,下面是我查询出来的

好啦,我们开始进行第一步的添加操作吧,下边是java代码:

package com.spring.ldap;


import com.novell.ldap.*;
import com.novell.ldap.LDAPConnection;

import java.io.UnsupportedEncodingException;

/**
 * @author jianning
 * @description 添加新条目的示例
 * @date 2018/11/8
 * @time 14:26
 */
public class LDAPAddEntry {

    public static void main(String[] args) {

        /**
         * ldap的连接属性,根据自己的情况更改
         */
        String ldapHost = "localhost";
        String loginDN = "cn=Manager,dc=maxcrc,dc=com";
        String password = "secret";
        String containerName = "dc=maxcrc,dc=com";

        int ldapPort = LDAPConnection.DEFAULT_PORT;
        int ldapVersion = LDAPConnection.LDAP_V3;
        LDAPConnection lc = new LDAPConnection();
        LDAPAttributeSet attributeSet = new LDAPAttributeSet();
        //这里是添加的用户属性,大家可以自行更改
        attributeSet.add(new LDAPAttribute("objectclass", new String("inetOrgPerson")));
        attributeSet.add(new LDAPAttribute("cn", "Wukong Sun"));
        attributeSet.add(new LDAPAttribute("sn", "Sun"));
        attributeSet.add(new LDAPAttribute("mail", "sjsky007@gmail.com"));
        attributeSet.add(new LDAPAttribute("labeledURI", "http://www.micmiu.com"));
        attributeSet.add(new LDAPAttribute("userPassword", "111111"));
        attributeSet.add(new LDAPAttribute("uid", "ning"));
        String dn = "uid=test,ou=Employee," + containerName;
        LDAPEntry newEntry = new LDAPEntry(dn, attributeSet);
        try {
            lc.connect(ldapHost, ldapPort);
            lc.bind(ldapVersion, loginDN, password.getBytes("UTF8"));
            System.out.println("login ldap server successfully.");
            lc.add(newEntry);
            System.out.println("Added object: " + dn + " successfully.");
        } catch (LDAPException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            System.out.println("Error: " + e.toString());
        } finally {
            try {
                if (lc.isConnected()) {
                    lc.disconnect();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

然后右键Run即可,打开ldap工具刷新一下即可看到我们刚刚添加的用户信息。你是不是也成功了呢?

本来打算一篇博客写完的,写到这里回车键不起作用了,我博客写的少,不知道是不是因为有字数限制,所以咱们下篇博客见~~~ 下篇博客:https://blog.csdn.net/IT_0417/article/details/83898849

 

  • 1
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值