[一]、概述
jldap 官网:http://www.openldap.org/jldap/
可以从官网下载源编译生成jar包,如果项目是用maven构建的,在pom.xml中增加如下内容即可:
1.<dependency>
2.<groupId>com.novell.ldap</groupId>
3.<artifactId>jldap</artifactId>
4.<version>4.3</version>
5.<type>jar</type>
6.<scope>compile</scope>
7.</dependency>
[二]、基本操作
为了演示基本的操作,需要搭建个LDAP服务,有关openLDAP在windows上的安装配置可参见:http://www.micmiu.com/enterprise-app/sso/openldap-windows-config/ ,我配置好演示用的LDAP基本信息可见客户端截图:
1.查询
java代码:LDAPSearchDemo.java
1 package com.micmiu.ldap
3 import java.io.UnsupportedEncodingException;
4 import java.util.Enumeration;
5 import java.util.Iterator;
7 import com.novell.ldap.LDAPAttribute;
8 import com.novell.ldap.LDAPAttributeSet;
9 import com.novell.ldap.LDAPConnection;
10 import com.novell.ldap.LDAPEntry;
11 import com.novell.ldap.LDAPException;
12 import com.novell.ldap.LDAPSearchResults;
13 import com.novell.ldap.util.Base64;
14
15 /**
16 * 查询条目示例 blog http://www.micmiu.com
17 *
18 * @author Michael
19 *
20 */
21 public class LDAPSearchDemo {
22
23 /**
24 *
25 * @param args
26 */
27 public static void main(String[] args) {
28
29 String ldapHost = "localhost";
30 String loginDN = "cn=Manager,dc=micmiu,dc=com";
31 String password = "secret";
32 String searchBase = "dc=micmiu,dc=com";
33 String searchFilter = "objectClass=*";
34
35 int ldapPort = LDAPConnection.DEFAULT_PORT;
36 // 查询范围
37 // SCOPE_BASE、SCOPE_ONE、SCOPE_SUB、SCOPE_SUBORDINATESUBTREE
38 int searchScope = LDAPConnection.SCOPE_SUB;
39
40 LDAPConnection lc = new LDAPConnection();
41 try {
42 lc.connect(ldapHost, ldapPort);
43 lc.bind(LDAPConnection.LDAP_V3, loginDN, password.getBytes("UTF8"));
44 LDAPSearchResults searchResults = lc.search(searchBase,
45 searchScope, searchFilter, null, false);
46
47 while (searchResults.hasMore()) {
48 LDAPEntry nextEntry = null;
49 try {
50 nextEntry = searchResults.next();
51 } catch (LDAPException e) {
52 System.out.println("Error: " + e.toString());
53 if (e.getResultCode() == LDAPException.LDAP_TIMEOUT
54 || e.getResultCode() == LDAPException.CONNECT_ERROR) {
55 break;
56 } else {
57 continue;
58 }
59 }
60 System.out.println("DN =: " + nextEntry.getDN());
61 System.out.println("|---- Attributes list: ");
62 LDAPAttributeSet attributeSet = nextEntry.getAttributeSet();
63 Iterator<LDAPAttribute> allAttributes = attributeSet.iterator();
64 while (allAttributes.hasNext()) {
65 LDAPAttribute attribute = allAttributes.next();
66 String attributeName = attribute.getName();
67
68 Enumeration<String> allValues = attribute.getStringValues();
69 if (null == allValu