https://www.cnblogs.com/miracle77hp/articles/11322944.html
Spring LDAP is a component of spring that implements LDAP operations.
When programming and operating MySQL, we may use some frameworks except JDBC, such as JbdcTemplate.
The implementation of JdbcTemplate is to pass in sql statement and RowMapper, and query returns the target list, or pass in sql and parameters to execute the update method. The advantage of JdbcTemplate is that it simplifies the code to connect to the database and avoids some common errors.
Similarly, the Spring LDAP framework provides a similar feature - LdapTemplate.
The advantages are the same. The advantage of Spring LdapTemplate is that it simplifies the code for interacting with LDAP.
Just configure the LdapTemplate and its attribute values in the xml file according to the way Spring configures JavaBean s before. This article will demonstrate how to use Springboot to define the LdapTemplate in Java code to complete the connection of Spring ldap to database services and related operations.
Here are the dependencies for using spring LDAP
<!-- spring ldapTemplate operation --> <dependency> <groupId>com.sun</groupId> <artifactId>ldapbp</artifactId> <version>1.0</version> </dependency> <dependency> <groupId>org.springframework.ldap</groupId> <artifactId>spring-ldap-core</artifactId> <version>2.3.2.RELEASE</version> </dependency>
First introduce some spring LDAP, because there are many tutorials on the Internet. There are spring LDAP and spring LDAP core in the given project dependencies, and there are version problems. The author uses the latest spring-ldap-2.3.2 RELEASE. It is recommended to use this latest version directly.
Spring ldap framework is the sum of spring's integrated ldap operations, including spring ldap core, spring ldap core tiger, spring ldap LDIF core, spring ldap ODM and other jar s. Generally, we only need to introduce spring ldap core in the project, which provides most functions. And so far, spring ldap is 2.3.2 Release is not in maven's central warehouse and is difficult to obtain. But spring ldap core is.
In addition, Spring LDAP 2.0 requires jdk version 1.6, and began to support ODM, and later introduced Spring ldap pool connection pool.
According to my attempt, there are great changes between these versions. In the new version, some key core classes may be moved to different package s; Some stupid functions completed by the old version may have better implementation or support in the new version, so some "stupid" implementations may be removed in the new version.
For example, LdapTemplate was originally on org springframework. The LDAP package is moved to the core package in the latest version. In spring LDAP core 2.0.2 The release version supports LDAP repository similar to JPA, but it is completely removed in the latest version of 2.3.2. However, the enhanced LdapTemplate in the new version makes LdapTemplate more powerful and can completely replace ldaptepository.
The following is to define the LdapTemplate in the way of Java code to connect to the LDAP server with Spring ldap
import com.cvte.csb.sim.ldap.constants.LdapConstans; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.ldap.core.ContextSource; import org.springframework.ldap.core.LdapTemplate; import org.springframework.ldap.core.support.LdapContextSource; import org.springframework.ldap.pool.factory.PoolingContextSource; import org.springframework.ldap.pool.validation.DefaultDirContextValidator; import org.springframework.ldap.transaction.compensating.manager.TransactionAwareContextSourceProxy; import java.util.HashMap; import java.util.Map; /** * LDAP Auto configuration class for * * Complete connection and generation of LdapTemplate */ @Configuration public class LdapConfiguration { private LdapTemplate ldapTemplate; @Bean public LdapContextSource contextSource() { LdapContextSource contextSource = new LdapContextSource(); Map<String, Object> config = new HashMap(); contextSource.setUrl(LdapConstans.LDAP_URL); contextSource.setBase(LdapConstans.BASE_DC); contextSource.setUserDn(LdapConstans.USER_NAME); contextSource.setPassword(LdapConstans.PASS_WORD); // The key sentence to solve garbled code config.put("java.naming.ldap.attributes.binary", "objectGUID"); contextSource.setPooled(true); contextSource.setBaseEnvironmentProperties(config); return contextSource; } @Bean public LdapTemplate ldapTemplate() { if (null == ldapTemplate) ldapTemplate = new LdapTemplate(contextSource()); return ldapTemplate; } }
Completing the bean definition of LdapTemplate is the most critical step. For subsequent operations, CRUD operations of LDAP directory tree are all completed by it.
Through the above code, complete the bean definition in the IOC container, and we can inject and use LdapTemplate externally.
The following shows how to complete CRUD function with LdapTemplate:
import com.cvte.csb.sim.ldap.attribute.LdapDeptAttributeMapper; import com.cvte.csb.sim.ldap.attribute.LdapUserAttributeMapper; import com.cvte.csb.sim.ldap.module.dto.LdapUser; import org.junit.Assert; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.ldap.core.DirContextAdapter; import org.springframework.ldap.core.DistinguishedName; import org.springframework.ldap.core.LdapTemplate; import org.springframework.ldap.filter.AndFilter; import org.springframework.ldap.filter.EqualsFilter; import java.util.List; public class ConfigTest extends BaseTest { @Autowired private LdapTemplate ldapTemplate; /** * Get all internal personnel * ou=Internal,ou=People */ @Test public void listUsers(){ AndFilter filter = new AndFilter(); filter.and(new EqualsFilter("objectClass", "person")); //Query all internal personnel List<LdapUser> users = ldapTemplate.search("ou=Internal,ou=People", filter.encode(), new LdapUserAttributeMapper()); for (LdapUser user: users ) { System.out.println(user); } // Assert.assertEquals(3056, users.size()); } /** * Find individual people by uid */ @Test public void findUser(){ //uid=00012047,ou=Internal,ou=People,o=cvte.com,o=isp DirContextAdapter obj = (DirContextAdapter) ldapTemplate.lookup("uid=00012047,ou=Internal,ou=People");//BASE_DC is not required System.out.println(obj); } /** * Find the department according to the department number o */ @Test public void findDept(){ //o=598b09cb12ab4364864d8ac73ecee00d,ou=Organizations,ou=People,o=cvte.com,o=isp DirContextAdapter obj = (DirContextAdapter) ldapTemplate.lookup("o=598b09cb12ab4364864d8ac73ecee00d,ou=Organizations");//BASE_DC is not required System.out.println(obj); } @Test public void listDepts(){ AndFilter filter = new AndFilter(); filter.and(new EqualsFilter("objectClass", "organization")); //search is to query according to the filter conditions. The first parameter is the dn of the parent node, which can be empty. When it is not empty, the query efficiency is higher List depts = ldapTemplate.search("", filter.encode(), new LdapDeptAttributeMapper()); System.out.println(depts.size()); // Assert.assertEquals(3056, depts.size()); } }
In ldap, there are two "query" concepts, search and lookup. Search is to query each entry with ldaptemplate, and lookup is to find an entry directly through DN.
In Ldap, adding and deleting are called binding and unbinding. These methods are all provided by LdapTemplate, and also provide various conditional filtering methods, which are not as good as findAll(),list(), etc.
We notice that findAll(),list() must return a Java util. List, including,
//Query all internal personnel
List users = ldapTemplate.search("ou=Internal,ou=People", filter.encode(), new LdapUserAttributeMapper());
It is also a return list. The list contains the query results. But the last article used JNDI to find out
Attributes attrs = ctx.getAttributes("uid=00012047,ou=Internal,ou=People");// Get a person
Spring LDAP is an encapsulation based on JNDI implementation. Where is it implemented to convert Attributes into Java Bean objects we need?
The answer is in new LdapUserAttributeMapper(), which realizes the conversion from query results to objects.
import com.cvte.csb.sim.ldap.module.dto.LdapUser; import org.springframework.ldap.core.AttributesMapper; import javax.naming.NamingException; import javax.naming.directory.Attributes; /** * Convert the result returned by ldap into the specified object */ public class LdapUserAttributeMapper implements AttributesMapper { /** * Convert a single attribute to a single object * @param attrs * @return * @throws NamingException */ public Object mapFromAttributes(Attributes attrs) throws NamingException { LdapUser user = new LdapUser(); if(attrs.get("uid") != null){ user.setUsername( attrs.get("uid").get().toString()); } if(attrs.get("cn") != null){ user.setUserCn( attrs.get("cn").get().toString()); } if(attrs.get("mobile") != null){ user.setMobile( attrs.get("mobile").get().toString()); } if(attrs.get("mail") != null){ user.setMail( attrs.get("mail").get().toString()); } if(attrs.get("employeeNumber") != null){ user.setUserNumber( attrs.get("employeeNumber").get().toString()); } if(attrs.get("type") != null){ user.setUserType( attrs.get("type").get().toString()); } if(attrs.get("py") != null){ user.setPinyin(attrs.get("py").get().toString()); } if(attrs.get("alias") != null){ user.setAlias(attrs.get("alias").get().toString()); } if(attrs.get("departmentNumber") != null){ user.setDeptId(attrs.get("departmentNumber").get().toString()); } if(attrs.get("departmentName") != null){ user.setDeptName(attrs.get("departmentName").get().toString()); } if(attrs.get("jobname") != null){ user.setPositionName(attrs.get("jobname").get().toString()); } if(attrs.get("modifyTimestamp") != null){ user.setModifyTimestamp(attrs.get("modifyTimestamp").get().toString()); } return user; } }
It can be seen that the transformation process is very cumbersome. It is nothing more than taking the Attributes queried by JNDI, constantly obtaining attribute values, and then setting them into Java objects; attrs.get("uid").get().toString() and then set.
How many attributes should be written in the mapper query and how many attributes should be written in each query. Moreover, if you want to query different columns because of different businesses, the implementation of the AttributesMapper interface must be rewritten. Is there a way to support reuse? The answer is yes. The next section shares spring LDAP, ODM, and object directory mapping.
spring-ldap-2.3.2.RELEASE Download all jar packages
http://download.csdn.net/download/ljheee/10150501
The latest version of spring LDAP official document:
https://docs.spring.io/spring-ldap/docs/2.3.2.RELEASE/reference/