Spring LDAPTemplate连接LDAP数据库demo

4 篇文章 0 订阅
2 篇文章 0 订阅

step1、创建maven工程


step2、修改pom文件

代码如下:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.tcs.platform</groupId>
  <artifactId>LDAPProject</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>LDAPProject Maven Webapp</name>
  <url>http://maven.apache.org</url>
 
  <build>
    <finalName>LDAPProject</finalName>
  </build>
 
  <dependencies>
 
      <dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
          <version>3.8.1</version>
          <scope>test</scope>
      </dependency>
    
      <!-- 添加Spring 对LDAP的支持 -->
      <dependency>
            <groupId>org.springframework.ldap</groupId>
            <artifactId>spring-ldap-core</artifactId>
            <version>1.3.1.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.ldap</groupId>
            <artifactId>spring-ldap-odm</artifactId>
            <version>1.3.1.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.ldap</groupId>
            <artifactId>spring-ldap-core-tiger</artifactId>
            <version>1.3.1.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.ldap</groupId>
            <artifactId>spring-ldap-ldif-batch</artifactId>
            <version>1.3.1.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.ldap</groupId>
            <artifactId>spring-ldap-ldif-core</artifactId>
            <version>1.3.1.RELEASE</version>
        </dependency>
      
        <!-- 添加日志的依赖包 -->
          <!-- <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.16</version>
        </dependency> -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-jcl</artifactId>
            <version>1.6.2</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>  
            <version>1.6.2</version>
        </dependency>
        
  </dependencies>

</project>


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

代码如下:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">

<beans>
    <bean  id="contextSource" class="org.springframework.ldap.core.support.LdapContextSource">
        <property name="url" value="ldap://localhost:389" />
        <property name="base" value="ou=citizen,dc=tcs,dc=com" />
        <property name="userDn" value="cn=Manager,ou=citizen,dc=tcs,dc=com" />
        <property name="password" value="secret" />
        <property name="referral" value="follow"></property>
    </bean>

    <bean id="ldapTemplate" class="org.springframework.ldap.core.LdapTemplate" >
        <constructor-arg>
            <ref bean="contextSource" />
        </constructor-arg>
    </bean>
    
    <bean id="ldapPerson" class="com.tcs.cloud.platform.Dao.LdapPersonDaoImpl">
        <property name="ldapTemplate">
            <ref bean="ldapTemplate" />
        </property>
    </bean>

</beans>

step4、创建LDAP接口LdapPersonFactory

代码如下:

package com.tcs.cloud.platform.Factory;

import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.tcs.cloud.platform.Dao.LdapPersonDao;
/**
 * 需要考虑线程安全
 * @author ki_boy@163.com
 *
 */
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[]{"123@tcs.com","234@tcs.com"});

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


尊重原创,谢谢合作!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值