下载地址 :http://www.springframework.org/ldap
用Spring LDAP最少需要:
UserDaoLdapImpl
package com.kingsoft.ldap; import java.util.List; import javax.naming.NamingException; import javax.naming.directory.Attributes; import org.springframework.ldap.core.AttributesMapper; import org.springframework.ldap.core.LdapTemplate; import cn.com.ldap.Preson.Person; /** * @author King_wangyao */ public class UserDaoLdapImpl { private LdapTemplate ldapTemplate; public void setLdapTemplate(LdapTemplate ldapTemplate) { this.ldapTemplate = ldapTemplate; } public List getAllPersonNames() { return ldapTemplate.search("", "(objectclass=person)", new AttributesMapper() { public Object mapFromAttributes(Attributes attrs) throws NamingException { return attrs.get("cn").get(); } }); } }
preson:
package com.kingsoft.ldap; public class Preson { public class Person { private String cn; private String sn; public String getCn() { return cn; } public void setCn(String cn) { this.cn = cn; } public String getSn() { return sn; } public void setSn(String sn) { this.sn = sn; } } }
applicationContext.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://192.168.16.XXX:389" /> <property name="base" value="OU=XXX,OU=XXX,OU=XXX,OU=XXX,DC=XXX,DC=XXX,DC=XXX" /> <property name="userName" value="XXX@headquarter" /> <property name="password" value="XXX" /> </bean> <bean id="ldapTemplate" class="org.springframework.ldap.core.LdapTemplate"> <constructor-arg ref="contextSource" /> </bean> <bean id="userDao" class="cn.com.ldap.UserDaoLdapImpl"> <property name="ldapTemplate"> <ref bean="ldapTemplate" /> </property> </bean> </beans>
main:
public static void main(String[] args) { ApplicationContext cxt = new ClassPathXmlApplicationContext("applicationContext.xml"); UserDaoLdapImpl userDao = (UserDaoLdapImpl)cxt.getBean("userDao"); List users = userDao.getAllPersonNames(); System.out.println(users.size()); }