第三章 通过DirContextAdapter进行简单的属性访问及操作
3.1介绍
一个鲜为人知的可能被低估的Java Ldap Api DirContextAdapter 可以去创建一个context,它被很少用的原因是实现它需要创建一个Dircontext实例,Spring Ldap弥补了它的不足:一个默认的DirContext实现称作DirContextAdapter,与之相对应的DirObjectFactory的 实现称作DefaultDirObjectFactory,同时使用 DefaultDirObjectFactory,DirContextAdapter将变得非常实用。
3.2 使用ContextMapper搜索和查找
通常DefaultDirObjectFactory是注册在ContextSource中,这意味着每当在Ldap树中发现Context,它的属性和唯一Dn将用于构建一个DirContextAdapter,这将使我们用
ContextMapper去转换查询到的值而不是AttributeMapper。
例 3.1 使用ContextMapper查询
packagecom.example.dao;
publicclassPersonDaoImplimplementsPersonDao{
...
privatestaticclassPersonContextMapperimplementsContextMapper{
publicObjectmapFromContext(Objectctx){
DirContextAdaptercontext=(DirContextAdapter)ctx;
Personp=newPerson();
p.setFullName(context.getStringAttribute("cn"));
p.setLastName(context.getStringAttribute("sn"));
p.setDescription(context.getStringAttribute("description"));
returnp;
}
}
publicPersonfindByPrimaryKey(
Stringname,Stringcompany,Stringcountry){
Namedn=buildDn(name,company,country);
returnldapTemplate.lookup(dn, newPersonContextMapper());
}
}
上面的代码展示了我们可以直接通过名字查找属性,而不需要Attributes 和 BasicAttribute ,这在我们面对多个属性值的时候非常有用。取得多属性通常我们要使用
NamingEnumeration循环,从attrbutes得到值。但是DirContextAdapter可以帮助我们做到这一点,使用getStringAttributes()或者getObjectAttributes()方法
例3.2 :使用getStringAttributes()取得属性的多个值
privatestaticclassPersonContextMapperimplementsContextMapper{
publicObjectmapFromContext(Objectctx){
DirContextAdaptercontext=(DirContextAdapter)ctx;
Personp=newPerson();
p.setFullName(context.getStringAttribute("cn"));