---
title: "spring ldap操作（一）目录测试环境搭建"
author: "xrb2008"
date: "2010-04-22T16:50:44Z"
tags: []
categories: ["企业架构"]
slug: "spring-ldap"
draft: false
lastmod: "2010-04-22T16:53:30Z"
id: 650632
url: "https://xrb2008.iteye.com/blog/650632"
---

Spring LDAP 是一个用于操作 LDAP 的 Java 框架。它是基于 Spring 的 JdbcTemplate 模式。这个框架能够帮助开发人员简化 looking up，closing contexts，looping through NamingEnumerations，encoding/decoding values与 filters 等操作。(理论上市面所有目录产品都适用，什么？你不知道ldap目录，请建议绕行)

 

下面是我搭建的一个简单的java测试目录的环境，只是试下能不能连上ldap，以及能否进行简单操作。功能比较简单

所需jar包：见附件工程

applicationContext.xml配置

```
<?xml version="1.0" encoding="UTF-8"?>
<beans
	xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

	<bean id="contextSource"  
        class="org.springframework.ldap.core.support.LdapContextSource">  
        <property name="url" value="ldap://10.201.4.*:389" />  
        <property name="base" value="o=*" />  
        <property name="userDn" value="cn=*"/>  
        <property name="password" value="***" />  
    </bean>  
  
    <bean id="ldapTemplate"  
        class="org.springframework.ldap.core.LdapTemplate">  
        <constructor-arg ref="contextSource" />  
    </bean>  
    

	<bean id="personDao" class="springLdapContext.PersonDaoImpl">
		  <property name="ldapTemplate">  
            <ref bean="ldapTemplate" />  
        </property>  

	</bean>
</beans>
```

 另外就是一个简单的操作类了**PersonDaoImpl**

```
public class PersonDaoImpl implements PersonDao {

	private LdapTemplate ldapTemplate;

	public static void main(String[] args) {
		ApplicationContext cxt = new ClassPathXmlApplicationContext("applicationContext.xml");   
		PersonDaoImpl personDao = (PersonDaoImpl)cxt.getBean("personDao");   
        List users = personDao.getAllPersonNames();   
        System.out.println(users.size());   

	}
	
	
	/*
	 * @see PersonDao#getAllPersonNames()
	 */
	public List getAllPersonNames() {
		EqualsFilter filter = new EqualsFilter("objectclass", "person");
		return ldapTemplate.search(DistinguishedName.EMPTY_PATH, filter.encode(), new AttributesMapper() {
			public Object mapFromAttributes(Attributes attrs) throws NamingException {
				return attrs.get("cn").get();
			}
		});
	}

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

 

 如果你查询的路径设置正确且下面有用户，应该就能输出用户数量了。注

&lt;property name="base" value="o=\*" /&gt;  base即查找的根路径