Spring-LDAP 的例子

下载地址 :http://www.springframework.org/ldap

用Spring LDAP最少需要:

  • spring-ldap(spring-ldap包)
  • spring-core(用于框架内部的丰富的工具类)
  • spring-beans(方便操作java beans的接口和类)
  • spring-context(增加通过一致API为应用对象获取资源的能力)
  • spring-dao(使经常性的错误处理跟使用中的数据访问分开的异常处理机制)
  • commons-logging(简单的日志处理,内部使用)

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());
}

  

你可能感兴趣的:(DAO,spring,bean,xml,框架)