1、创建新项目TestOpenLdap;

2、新建测试类TestOpenLdap.java;

3、编写测试程序。代码见附件。

package com.suresec.openldap;import java.util.Hashtable;import javax.naming.Context;import javax.naming.NamingException;import javax.naming.directory.BasicAttribute;import javax.naming.directory.BasicAttributes;import javax.naming.directory.DirContext;import javax.naming.directory.InitialDirContext;public class TestOpenLDAP {final private static String account = "Manager";final private static String password = "python";final private static String root = "dc=python,dc=com";public TestOpenLDAP(){//init();}public DirContext getCtx(){DirContext ctx = null;Hashtable env = new Hashtable();env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");env.put(Context.PROVIDER_URL, "ldap://192.168.1.45:389/");env.put(Context.SECURITY_AUTHENTICATION, "simple");env.put(Context.SECURITY_PRINCIPAL, "cn="+account+","+root);env.put(Context.SECURITY_CREDENTIALS, password);try {ctx = new InitialDirContext(env);System.out.println("认证成功");} catch (Exception e) {// TODO Auto-generated catch blockSystem.out.println("认证失败:"+e.toString());return null;}return ctx;}public void add(DirContext ctx){try {String newUserName = "hi";BasicAttributes attrs = new BasicAttributes();BasicAttribute objclassSet = new BasicAttribute("objectClass");objclassSet.add("top");objclassSet.add("organizationalUnit");attrs.put(objclassSet);attrs.put("ou",newUserName);ctx.createSubcontext("ou=" + newUserName+","+root, attrs);} catch (NamingException e) {// TODO Auto-generated catch blockSystem.out.println("Exception in add():"+e);}}public void delete(DirContext ctx){try {ctx.destroySubcontext("ou=hi,dc=python,dc=com");} catch (NamingException e) {// TODO Auto-generated catch blocke.printStackTrace();}}public void close(DirContext ctx){try {if(ctx != null){ctx.close();}} catch (NamingException e) {// TODO Auto-generated catch blockSystem.out.println("NamingException in close():"+e);}}/*** @param args*/public static void main(String[] args) {// TODO Auto-generated method stubTestOpenLDAP testOpenLdap = new TestOpenLDAP();DirContext ctx = testOpenLdap.getCtx();testOpenLdap.add(ctx);testOpenLdap.close(ctx);}}

4、运行测试程序,结果如下所示: