Spring LDAPTemplate连接LDAP数据库demo

step1、创建maven工程


step2、修改pom文件

代码如下:

  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  4.0.0
  com.tcs.platform
  LDAPProject
  war
  0.0.1-SNAPSHOT
  LDAPProject Maven Webapp
  http://maven.apache.org
 
 
    LDAPProject
 

 
 
 
     
          junit
          junit
          3.8.1
          test
     

    
     
     
            org.springframework.ldap
            spring-ldap-core
            1.3.1.RELEASE
       

        
            org.springframework.ldap
            spring-ldap-odm
            1.3.1.RELEASE
       

        
            org.springframework.ldap
            spring-ldap-core-tiger
            1.3.1.RELEASE
       

        
            org.springframework.ldap
            spring-ldap-ldif-batch
            1.3.1.RELEASE
       

        
            org.springframework.ldap
            spring-ldap-ldif-core
            1.3.1.RELEASE
       

      
       
          
        
            org.slf4j
            slf4j-jcl
            1.6.2
        

        
            org.slf4j
            slf4j-api  
            1.6.2
        

        
 




step3、创建LDAP的配置文件ldapContext.xml

代码如下:





   
       
       
       
       
        
   

   
       
           
       

   

    
   
       
           
       

   




step4、创建LDAP接口LdapPersonFactory

代码如下:

package com.tcs.cloud.platform.Factory;

import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.tcs.cloud.platform.Dao.LdapPersonDao;
/**
 * 需要考虑线程安全
 * @author [email protected]
 *
 */
public class LdapPersonFactory {

    private static LdapPersonDao ldapPersonDao = null;

    public static LdapPersonDao getPersonDao(){
        if (ldapPersonDao == null){
            ClassPathXmlApplicationContext ctx
             = new ClassPathXmlApplicationContext(new String[] {"ldapContext.xml"});
            ldapPersonDao = (LdapPersonDao)ctx.getBean("ldapPerson");
        }
        return ldapPersonDao;
    }

}


step5、创建DAO接口LdapPersonDao

代码如下:

package com.tcs.cloud.platform.Dao;

import java.util.List;

import org.springframework.ldap.NamingException;

import com.tcs.cloud.platform.Entity.Person;

/**
 * Data Access Object interface for the Person entity.
 *
 * @author ki_boy
 *
 */
public interface LdapPersonDao {
    void create(Person person) throws NamingException;

    void update(Person person) throws NamingException;

    void delete(Person person) throws NamingException;

    List getAllPersonNames() throws NamingException;

    List findAll() throws NamingException;

    boolean isUserCnExist(String cn);

}

step6、创建DAO接口的实现LdapPersonDaoImpl

代码如下:

package com.tcs.cloud.platform.Dao;

import java.util.List;

import javax.naming.Name;
import javax.naming.NamingException;
import javax.naming.directory.Attributes;
import javax.naming.directory.BasicAttribute;
import javax.naming.directory.DirContext;
import javax.naming.directory.ModificationItem;
import javax.naming.directory.SearchControls;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ldap.NameNotFoundException;
import org.springframework.ldap.control.PagedResultsCookie;
import org.springframework.ldap.control.PagedResultsDirContextProcessor;
import org.springframework.ldap.core.AttributesMapper;
import org.springframework.ldap.core.CollectingNameClassPairCallbackHandler;
import org.springframework.ldap.core.ContextMapper;
import org.springframework.ldap.core.ContextMapperCallbackHandler;
import org.springframework.ldap.core.DirContextAdapter;
import org.springframework.ldap.core.DistinguishedName;
import org.springframework.ldap.core.LdapTemplate;
import org.springframework.ldap.core.support.LdapContextSource;
import org.springframework.ldap.filter.AndFilter;
import org.springframework.ldap.filter.EqualsFilter;
import org.springframework.ldap.filter.OrFilter;
import org.springframework.ldap.filter.WhitespaceWildcardsFilter;

import com.tcs.cloud.platform.Entity.Person;

public class LdapPersonDaoImpl implements LdapPersonDao {
    private LdapTemplate ldapTemplate;
    private static final Logger log = LoggerFactory.getLogger(LdapPersonDaoImpl.class);

    public void create(Person person) {
        Name dn = buildDn(person);
        DirContextAdapter context = new DirContextAdapter(dn);
        mapToContext(person, context, true);
        ldapTemplate.bind(dn, context, null);
    }

    public void update(Person person) {
        Name dn = buildDn(person);
        DirContextAdapter context = (DirContextAdapter) ldapTemplate.lookup(dn);
        mapToContext(person, context, false);
        ldapTemplate.modifyAttributes(dn, context.getModificationItems());
    }

    public void delete(Person person) {
        ldapTemplate.unbind(buildDn(person));
    }

    public List getAllPersonNames() {
        EqualsFilter filter = new EqualsFilter("objectclass", "localPerson");
        return ldapTemplate.search(DistinguishedName.EMPTY_PATH,
                filter.encode(), new AttributesMapper() {
                    public Object mapFromAttributes(Attributes attrs)
                            throws NamingException {
                        return attrs.get("cn").get();
                    }
                });
    }

    public List findAll() {
        EqualsFilter filter = new EqualsFilter("objectclass", "localPerson");
        return ldapTemplate.search(DistinguishedName.EMPTY_PATH,
                filter.encode(), getContextMapper());
    }

    public Person findByPrimaryKey(String cn) {
        Person p = (Person) ldapTemplate.lookup("cn=" + cn, getContextMapper());
        return p;
    }

    private ContextMapper getContextMapper() {
        return new PersonContextMapper();
    }

    private DistinguishedName buildDn(Person person) {
        return buildDn(person.getCn());
    }

    private DistinguishedName buildDn(String cn) {
        DistinguishedName dn = new DistinguishedName();
        dn.add("cn", cn);
        if (log.isDebugEnabled())
            log.debug("dn=" + dn.toString());
        return dn;
    }

    /**
     * 添加所有属性 密码修改单独维护
     *
     * @param person
     * @param context
     */
    private void mapToContext(Person person, DirContextAdapter context,boolean isCreate) {
        context.setAttributeValues("objectclass", new String[] { "top","person" });
        context.setAttributeValues("objectclass", new String[] { "person","localPerson" });
        context.setAttributeValue("cn", person.getCn());
        context.setAttributeValue("uid", person.getUid());
        context.setAttributeValue("sn", person.getSn());
        if (isCreate) {
            context.setAttributeValue("userPassword", person.getUserPassword());
        }
        context.setAttributeValue("userType", person.getUserType());
        context.setAttributeValues("mail", person.getMail());
        context.setAttributeValue("mobile", person.getMobile());
        context.setAttributeValue("sex", person.getSex());
        context.setAttributeValue("age", person.getAge());
    }

    /**
     * 查询不要返回密码信息
     */
    private static class PersonContextMapper implements ContextMapper {

        public Object mapFromContext(Object ctx) {
            DirContextAdapter context = (DirContextAdapter) ctx;
            Person person = new Person();
            // context.getAttributes() 通过属性赋值 TODO 减少代码
            person.setCn(context.getStringAttribute("cn"));
            person.setSn(context.getStringAttribute("sn"));
            person.setUid(context.getStringAttribute("uid"));
            // person.setUserPassword(context.getStringAttribute("userPassword"));
            person.setDescription(context.getStringAttribute("description"));
            person.setUserType(context.getStringAttribute("userType"));
            person.setAge(context.getStringAttribute("age"));
            person.setMail(context.getStringAttributes("mail"));
            person.setMobile(context.getStringAttribute("mobile"));
            return person;
        }
    }

    public boolean isUserCnExist(String cn) {
        try {
            ldapTemplate.lookup("cn=" + cn);
        } catch (NameNotFoundException e) {
            log.info(" isUserCnExist:" + e.getCause());
            return false;
        }
        return true;
    }

    public void setLdapTemplate(LdapTemplate ldapTemplate) {
        this.ldapTemplate = ldapTemplate;
    }

}


step7、创建实体Bean(Person)

这个根据自己的实际情况,如userName,userPassword,sex等字段,并生成相应的getter和setter方法。


step8、创建测试类

代码如下:

package com.tcs.cloud.platform.Dao;

import java.util.List;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.tcs.cloud.platform.Entity.Person;

public class PersonDaoImplTest {

    /**
     * @param args
     */
    public static void main(String[] args) {
        ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(new String[] {"ldapContext.xml"});
            LdapPersonDao ldapPerson = (LdapPersonDao)ctx.getBean("ldapPerson");
            PersonDaoImplTest test = new PersonDaoImplTest();
            //test.findByUniqueId(ldapPerson);
            test.testCreate(ldapPerson, "ki_boy");
    }


    public void testCreate(LdapPersonDao ldapPerson,String cn) {
        Person person = new Person();
        person.setCn(cn);
        person.setSn("cc-sn");
        person.setUserPassword("111111");
        person.setUid(cn);
        person.setAge("30");
        person.setSex("女");
        person.setMobile("12304996050");
        person.setMail(new String[]{"[email protected]","[email protected]"});

        try {
            ldapPerson.create(person);
            System.out.println("person create success");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("person create fail.." + e.getCause());
        }
    }
   
}


尊重原创,谢谢合作!

你可能感兴趣的:(java,ldap,spring,ldap,spring,maven,database)