Connecting LDAP server from java application

后端 未结 3 1103
误落风尘
误落风尘 2020-12-15 00:29

I am building an application based on GXT (J2EE). Now the problem is that I have to connect the application to a LDAP server. Can you tell me how to connect a LDAP server fr

3条回答
  •  忘掉有多难
    2020-12-15 01:16

    • Connection to a LDAP server is made using JNDI (Java Naming and Directory Interface) APIs in Java.
    • The JNDI’s interfaces, classes and exceptions are available in the following packages come with JDK:

      • javax.naming.*
      • javax.naming.directory.*
    • That means we don’t have to use any external libraries for working with LDAP servers, in most cases.

    • That specifies URL of a LDAP server consists of hostname on which LDAP Server is running port number. A well known port number of the Lightweight Directory Access Protocol is 389 which is default.

    • Also need to specify some environment properties for the connection and authentication in a Hashtable object.

    Here is the sample code:

    import javax.naming.*;
    import javax.naming.ldap.*;
    import javax.naming.directory.*;
    
    public class Ldap
    {
        public static void main(String[]args)
        {
            Hashtable environment = new Hashtable();
    
            environment.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
            environment.put(Context.PROVIDER_URL, "ldap://:389");
            environment.put(Context.SECURITY_AUTHENTICATION, "simple");
            environment.put(Context.SECURITY_PRINCIPAL, "");
            environment.put(Context.SECURITY_CREDENTIALS, "");
    
            try 
            {
                DirContext context = new InitialDirContext(environment);
                System.out.println("Connected..");
                System.out.println(context.getEnvironment());
                context.close();
            } 
            catch (AuthenticationNotSupportedException exception) 
            {
                System.out.println("The authentication is not supported by the server");
            }
    
            catch (AuthenticationException exception)
            {
                System.out.println("Incorrect password or username");
            }
    
            catch (NamingException exception)
            {
                System.out.println("Error when trying to create the context");
            }
        }
    }
    

提交回复
热议问题