错误:需要在环境或系统属性LDAP和JNDI中指定类名

use*_*718 5 java jndi ldap

这是我的代码:

     public class TestConnection {

public static void main(String[] args) {
    String password = "s3cret";
    Map<String, String> env = new HashMap<String, String>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, "ldap://localhost:389/dc=userdev,dc=local");
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    //env.put(Context.SECURITY_PRINCIPAL, "uid="+ username +"cn=users"); // replace with user DN
    env.put(Context.SECURITY_PRINCIPAL, "cn=dcmanager,cn=users,dc=userdev,dc=local"); // replace with user DN
    env.put(Context.SECURITY_CREDENTIALS, password);

    DirContext ctx = null;
    try {
       ctx = new InitialDirContext();
    } catch (NamingException e) {
       // handle
    }
    try {
       SearchControls controls = new SearchControls();
       controls.setSearchScope( SearchControls.SUBTREE_SCOPE);
       ctx.search( "", "(objectclass=person)", controls);
       // no need to process the results
    } catch (NameNotFoundException e) {
        e.printStackTrace();
        System.out.println("catch 1");
       // The base context was not found.
       // Just clean up and exit.
    } catch (NamingException e) {
        System.out.println("catch 2");
        e.printStackTrace();
       // exception handling
    } finally {
       // close ctx or do Java 7 try-with-resources http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
    }

}

    }
Run Code Online (Sandbox Code Playgroud)

我收到此错误(第2次捕获): javax.naming.NoInitialContextException:需要在环境或系统属性中,或作为applet参数或在应用程序资源文件中指定类名称:java.naming.factory.initial

我已经寻找了很多解决方案,但是我没有得到错误。问题出在哪里?也许是上下文,但是我认为代码是完全正确的。

Pri*_*esh 4

您必须使用已填充的环境映射来构造InitialDirContext对象。即使用以下代码来构造它;

ctx = new InitialDirContext(env);