首页 > 代码库 > 2017.4.10 spring-ldap官方文档学习
2017.4.10 spring-ldap官方文档学习
官网:http://www.springframework.org/ldap
官方文档及例子(重要):http://docs.spring.io/spring-ldap/docs/2.1.0.RELEASE/reference/
JAVA文档(重要):http://docs.spring.io/spring-ldap/docs/2.1.0.RELEASE/apidocs/
GitHub(大量例子):https://github.com/spring-projects/spring-ldap
Spring LDAP Reference
2.基本使用
2.1 使用AttributesMapper进行search和lookup
(1)通过search返回一个属性值
1 import static org.springframework.ldap.query.LdapQueryBuilder.query; 2 3 public class PersonRepoImpl implements PersonRepo{ 4 private LdapTemplate ldapTemplate; 5 6 public void setLdapTemplate(LdapTemplate ldapTemplate){ 7 this.ldapTemplate = ldapTemplate; 8 } 9 10 public List<String> getAllPersonNames(){ 11 return ldapTemplate.search({ 12 query().where("objectclass").is("person"), 13 new AttributeMapper<String>(){ 14 public String mapFromAttributes(Attribute attrs)throws NamingException{ 15 return (String) attrs.get("cn").get(); 16 } 17 } 18 } 19 }); 20 } 21 }
(2)通过search返回一个Person对象
1 package com.example.repo; 2 import static org.springframework.ldap.query.LdapQueryBuilder.query; 3 4 public class PersonRepoImpl implements PersonRepo { 5 private LdapTemplate ldapTemplate; 6 ... 7 private class PersonAttributesMapper implements AttributesMapper<Person> { 8 public Person mapFromAttributes(Attributes attrs) throws NamingException { 9 Person person = new Person(); 10 person.setFullName((String)attrs.get("cn").get()); 11 person.setLastName((String)attrs.get("sn").get()); 12 person.setDescription((String)attrs.get("description").get()); 13 return person; 14 } 15 } 16 17 public List<Person> getAllPersons() { 18 return ldapTemplate.search(query() 19 .where("objectclass").is("person"), new PersonAttributesMapper()); 20 } 21 }
(3)通过lookup返回一个Person对象
在ldap中,有两个"查询"概念,search和lookup。search是ldaptemplate对每一个entry进行查询,lookup是通过DN直接找到某个条目。
"Entries in LDAP are uniquely identified by their distinguished name (DN). If you have the DN of an entry, you can retrieve(找回) the entry directly without searching for it. This is called a lookup in Java LDAP."
在下面的lookup代码中,ldap会跳过为AttributesMapper查找属性。
1 package com.example.repo; 2 3 public class PersonRepoImpl implements PersonRepo { 4 private LdapTemplate ldapTemplate; 5 ... 6 public Person findPerson(String dn) { 7 return ldapTemplate.lookup(dn, new PersonAttributesMapper()); 8 } 9 }
2.2 创建LDAP Queries
ldap的search 包含许多参数,比如:
1 Base LDAP path 基本路径(search应该从LDAP树的哪里开始) 2 Search scope 查询范围(search应该进行到LDAP树的哪一层) 3 returned attributes要返回的属性 4 Search filter 查询过滤器
2017.4.10 spring-ldap官方文档学习