使用java api操作LDAP

参考链接:
https://my.oschina.net/xpbug/blog/86193

下面以用户test为例:uid=test,ou=tester,dc=ibm,dc=com
执行类

public class TestLdap {
	public static void main(String[] args) throws NamingException {
		Ldap ldap = Factory.createInstance();
		
		ldap.connect();
		try {
			// add uid=test,ou=tester,dc=ibm,dc=com
			ldap.add();
			// search uid=test
		    ldap.search();
		    // update cn with new value of "changed name"
		    ldap.update();
		    // search uid=test to see cn value.
		    ldap.search();
		    // delete uid=test,ou=tester,dc=ibm,dc=com
		    ldap.delete();
		    // search again.
		    ldap.search();
		} finally {
			ldap.close();
		}
	}
}

接口

public interface Ldap {
	public void connect() throws NamingException;
	public void search() throws NamingException;
	public void update() throws NamingException;
	public void add() throws NamingException;
	public void delete() throws NamingException;
	public void close() throws NamingException;
}

静态工厂模式

public class Factory {
	private static Ldap instance;
	public synchronized static Ldap createInstance() {
		if (instance == null) {
			try {
				instance = (Ldap) Class.forName("ldap.LdapImpl").newInstance();
			} catch (Exception e) {
				throw new RuntimeException(e);
			} 
		}
		return instance;
	}
}

接口实现

public class LdapImpl implements Ldap {
	private DirContext ds;

	@Override
	public void search() throws NamingException {
		System.out.println("Searching...");
		SearchControls searchCtls = new SearchControls();

		// Specify the search scope
		searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
		// specify the LDAP search filter
		String searchFilter = "uid=test";

		// Specify the Base for the search
		String searchBase = "dc=ibm,dc=com";

		// Specify the attributes to return
		String returnedAtts[] = { "cn" };
		searchCtls.setReturningAttributes(returnedAtts);

		// Search for objects using the filter
		NamingEnumeration<SearchResult> entries = ds.search(searchBase,
				searchFilter, searchCtls);

		// Loop through the search results
		while (entries.hasMoreElements()) {
			SearchResult entry = entries.next();
			System.out.println(">>>" + entry.getName());
			// Print out the groups
			Attributes attrs = entry.getAttributes();
			if (attrs != null) {
				for (NamingEnumeration<? extends Attribute> names = attrs
						.getAll(); names.hasMore();) {
					Attribute attr = names.next();
					System.out.println("AttributeID: " + attr.getID());
					for (NamingEnumeration<?> e = attr.getAll(); e.hasMore();) {
						System.out.println("Attributes:" + e.next());
					}
				}
			}
		}
		System.out.println("Search complete.");
	}

	@Override
	public void update() throws NamingException {
		System.out.println("Updating...");
		 ModificationItem[] mods = new ModificationItem[1];
         Attribute attr = new BasicAttribute("cn", "changed value");
         
         // Support add, replace and remove an attribute.
         mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, attr);
         ds.modifyAttributes("uid=test,ou=tester,dc=ibm,dc=com", mods);
		System.out.println("Updated.");
	}

	@Override
	public void add() throws NamingException {
		System.out.println("Adding...");
		Attributes attrs = new BasicAttributes();
		attrs.put("uid", "test");
		attrs.put("sn", "test");
		attrs.put("cn", "test test");
		attrs.put("userPassword", "111111".getBytes());
		// the following attribute has two values
		Attribute objclass = new BasicAttribute("objectClass");
		objclass.add("inetOrgPerson");
		attrs.put(objclass);

		this.ds.createSubcontext("uid=test,ou=tester,dc=ibm,dc=com", attrs);
		System.out.println("Add complete.");
	}

	@Override
	public void delete() throws NamingException {
		System.out.println("Deleting...");
		this.ds.destroySubcontext("uid=test,ou=tester,dc=ibm,dc=com");
		System.out.println("Deleted.");
	}

	@Override
	public synchronized void connect() throws NamingException {
		System.out.println("connecting...");
		if (ds == null) {
			Hashtable<String, Object> env = new Hashtable<String, Object>(11);
			env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
			env.put(Context.PROVIDER_URL, "ldap://localhost:389");
			env.put(Context.SECURITY_AUTHENTICATION, "simple");
			env.put(Context.SECURITY_PRINCIPAL, "cn=Manager,dc=ibm,dc=com");
			env.put(Context.SECURITY_CREDENTIALS, "secret");

			ds = new InitialDirContext(env);
			// ds = (DirContext) initial.lookup("ldap://localhost:389");
		}
		System.out.println("connected.");
	}

	@Override
	public void close() throws NamingException {
		System.out.println("closing...");
		ds.close();
		System.out.println("closed.");
	}

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
LDAP(Lightweight Directory Access Protocol)是一种应用层协议,用于访问和维护分布式目录信息服务。在Java中,可以使用JNDI(Java Naming and Directory Interface)API来访问LDAP服务。 下面是使用JNDI API实现LDAP添加数据的示例代码: ```java import javax.naming.*; import javax.naming.directory.*; public class LdapAddDataExample { public static void main(String[] args) { // 设置LDAP连接参数 String ldapUrl = "ldap://localhost:389"; String ldapUserDn = "cn=admin,dc=example,dc=com"; String ldapPassword = "password"; String ldapBaseDn = "ou=people,dc=example,dc=com"; // 创建LDAP连接 DirContext ctx = null; try { // 初始化环境 Hashtable<String, String> env = new Hashtable<String, String>(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, ldapUrl); env.put(Context.SECURITY_AUTHENTICATION, "simple"); env.put(Context.SECURITY_PRINCIPAL, ldapUserDn); env.put(Context.SECURITY_CREDENTIALS, ldapPassword); ctx = new InitialDirContext(env); // 创建LDAP条目 Attributes attrs = new BasicAttributes(); attrs.put("cn", "John Doe"); attrs.put("sn", "Doe"); attrs.put("givenName", "John"); attrs.put("mail", "john.doe@example.com"); attrs.put("userPassword", "password"); Attribute oc = new BasicAttribute("objectClass"); oc.add("inetOrgPerson"); attrs.put(oc); String entryDn = "cn=John Doe," + ldapBaseDn; ctx.createSubcontext(entryDn, attrs); System.out.println("LDAP条目添加成功!"); } catch (NamingException e) { e.printStackTrace(); } finally { if (ctx != null) { try { ctx.close(); } catch (NamingException e) { e.printStackTrace(); } } } } } ``` 在上面的代码中,首先设置了LDAP连接参数,然后创建了LDAP连接。接着,创建了LDAP条目的属性,并将其添加到指定的LDAP目录下。 需要注意的是,要使用JNDI API访问LDAP服务,需要在项目中引入javax.naming和javax.naming.directory包。同时,还需要在项目中引入LDAP服务器的JAR包,例如OpenLDAP的JAR包为:openldap.jar。 另外,需要根据实际情况修改代码中的LDAP连接参数和LDAP条目属性。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

这个操蛋的人生!!!

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值