1, build LDAP Service, I use the system is Ubuntu14.04, specific can refer to this article: ubuntu14.04 to build LDAP services, follow the steps to no problem.
After installation The Access address is: http://10.8.12.147/phpldapadmin/
Name:cn=admin,dc=dianrong,dc=com
password:123456
2, install Ldapsoft LDAP Admin tool, official website download address: http://www.ldapsoft.com/download.html
Click New Connection (new Connection) and follow the configuration below:
The first time you come in, there will only be the cn=admin below.
3, the use of SPRING-LDAP to realize the deletion and modification (no use of annotations)
Model class:
/** * Created by DRJR on 5/17/17.
*/public class User {private String fullName;
Private String LastName;
Private String description;
Private String country;
Private String Company;
Private String phone;
Public String GetDescription () {return description;
} public void SetDescription (String description) {this.description = description;
} public String Getfullname () {return fullName;
} public void Setfullname (String fullName) {this.fullname = FullName;
} public String Getlastname () {return lastName;
} public void Setlastname (String lastName) {this.lastname = LastName;
} public String Getcompany () {return company;
public void Setcompany (String company) {this.company = Company;
} public String Getcountry () {return country; } public void Setcountry (String country) {this.country = CoUntry;
} public String Getphone () {return phone;
} public void Setphone (String phone) {this.phone = phone; }
}
Defines the interface classes that manipulate LDAP:
Public interface Userdao {
void Create (user user);
void update (user user);
void Delete (String fullName);
List<string> getallusernames ();
List<user> findAll ();
User Findbyprimarykey (String fullname);
}
Interface Implementation class:
public class Userdaoimpl implements Userdao {private ldaptemplate ldaptemplate;
@Override public void Create (user user) {Name DN = BUILDDN (User.getfullname ());//Generate entry uniquely identified, somewhat similar to MySQL's primary key ID Dircontextadapter context = new Dircontextadapter (DN); Build the Adapter object Maptocontext (user, context) based on the DN provided by the body; Sets the property value for the adapter object Ldaptemplate.bind (DN, context, NULL);
Insert Data} @Override public void update (user user) {Name DN = BUILDDN (User.getfullname ());
Dircontextadapter context = (Dircontextadapter) ldaptemplate.lookup (DN);
Maptocontext (user, context);
Ldaptemplate.modifyattributes (DN, Context.getmodificationitems ());
} @Override public void Delete (String fullName) {ldaptemplate.unbind (BUILDDN (fullName));
} @Override Public list<string> getallusernames () {return Ldaptemplate.search (query () . attributes ("cn"). WHERE ("OBjectclass "). Is (" person "), new Attributesmapper<string> () {@Override Public String mapfromattributes (Attributes Attributes) throws Namingexception {return a
Ttributes.get ("cn"). Get (). toString ();
}
});
} @Override Public list<user> findAll () {return Ldaptemplate.search (query ()
. WHERE ("objectclass"). Is ("person"), user_context_mapper);
} @Override Public User Findbyprimarykey (String fullname) {ldapname DN = BUILDDN (fullname);
Return Ldaptemplate.lookup (DN, user_context_mapper); Private LDAPName Builddn (String fullName) {return ldapnamebuilder.newinstance (). Add ("cn",
FullName). build (); } private void Maptocontext (user user, Dircontextadapter context) {context.setattributevalues ("objectclass", New StrinG[] {"Top", "person"});
Context.setattributevalue ("cn", User.getfullname ());
Context.setattributevalue ("SN", User.getlastname ());
Context.setattributevalue ("description", User.getdescription ());
Context.setattributevalue ("Telephonenumber", User.getphone ());
} private Final static contextmapper<user> User_context_mapper = new Abstractcontextmapper<user> () {
@Override Public User Domapfromcontext (Dircontextoperations context) {User user = new User ();
User.setfullname (Context.getstringattribute ("cn"));
User.setlastname (Context.getstringattribute ("SN"));
User.setdescription (Context.getstringattribute ("description"));
User.setphone (Context.getstringattribute ("telephonenumber"));
return user;
}
};
public void Setldaptemplate (Ldaptemplate ldaptemplate) {this.ldaptemplate = ldaptemplate; } public Ldaptemplate GetldaPtemplate () {return ldaptemplate; }
}
Front-end ingress controller layer:
@Controller @RequestMapping (value = "Users") public class Testspringldapcontroller {@Autowired private Userdao u
Serdao;
@RequestMapping ("/adduser") public String AddUser () {User user = GetUser ();
Userdao.create (user);
Return "Success"; } @RequestMapping ("/showuser") @ResponseBody public Modelmap showuser (@RequestParam (value = "FullName", Requi
Red = True) String fullName {User user = Userdao.findbyprimarykey (fullName);
return new Modelmap ("user", user); } @RequestMapping ("/updatephonenumber") public String Updatephonenumber (@RequestParam (value = "FullName", require
D = True) String fullName {User user = Userdao.findbyprimarykey (fullName);
User.setphone (Stringutils.join (new string[] {user.getphone (), "0"}));
Userdao.update (user);
Return "Success"; } @RequestMapping ("/removeuser") public String Removeperson (@RequestParam (value = "FullName", requireD = True) String fullName {userdao.delete (fullName);
Return "Success"; } @RequestMapping ("/getall") @ResponseBody public String getAll () throws IOException {Objectmapper m
Apper = Getdefaultobjectmapper ();
list<user> users = Userdao.findall ();
Return mapper.writevalueasstring (users); } @RequestMapping ("/getallname") @ResponseBody public String getallname () throws IOException {Object
Mapper Mapper = Getdefaultobjectmapper ();
list<string> userNames = Userdao.getallusernames ();
Return mapper.writevalueasstring (UserNames);
Private User GetUser () {User user = new User ();
User.setfullname ("Curry");
User.setlastname ("Stephone");
User.setcompany ("Company1");
User.setcountry ("Sweden");
User.setdescription ("Test user");
return user; } public static Objectmapper Getdefaultobjectmapper () {ObjectmapperMapper = new Objectmapper ();
Mapper.setserializationinclusion (JsonSerialize.Inclusion.NON_EMPTY);
Set the Mapper.configure (SerializationConfig.Feature.WRITE_NULL_MAP_VALUES, false) to convert the MAP to JSON only when the value is not equal to NULL;
Mapper.configure (JsonGenerator.Feature.ESCAPE_NON_ASCII, true);
Mapper.setdateformat (New SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss"));
Set properties can not be mapped to PO when no error mapper.disable (DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES);
return mapper; }
}
With the Gradle build, so the Build.gradle configuration is as follows:
Group ' DIANRONGDENGHB ' version ' 1.0-snapshot ' Apply plugin: ' java ' Apply plugin: ' War ' sourcecompatibility = 1.8 Reposi Tories {mavencentral ()} repositories {Jcenter () Maven {URL ' https://repo.spring.io/libs-milestone '}} dependencies {Testcompile group: ' JUnit ', Name: ' JUnit ', Version: ' 4.12 ' compile group: ' Org.springfra Mework.ldap ', Name: ' Spring-ldap-core ', version: ' 2.1.0.RELEASE ' compile group: ' Org.springframework.ldap ', Name: ' SPR Ing-ldap-test ', version: ' 2.1.0.RELEASE ' compile group: ' Org.springframework ', Name: ' Spring-context ', version: ' 4.2.4 . RELEASE ' compile group: ' Org.springframework ', Name: ' Spring-webmvc ', version: ' 4.2.4.RELEASE ' compile group: ' org . Springframework ', Name: ' Spring-web ', version: ' 4.2.4.RELEASE ' compile group: ' Org.springframework ', Name: ' spring-be Ans ', version: ' 4.2.4.RELEASE ' compile ' org.springframework:spring-core:4.2.4.release ' compile group: ' ORG.SPRINGF Ramework.data ', Name: 'Spring-data-commons ', version: ' 1.11.4.RELEASE ' compile group: ' Javax.servlet ', Name: ' Jstl ', Version: ' 1.2 ' Compi Le group: ' Com.fasterxml.jackson.core ', Name: ' Jackson-databind ', version: ' 2.4.3 ' compile group: ' Org.codehaus.jackso N ', Name: ' JACKSON-MAPPER-ASL ', version: ' 1.9.13 ' compile group: ' Org.codehaus.jackson ', Name: ' JACKSON-CORE-ASL ', ver Sion: ' 1.9.13 ' providedcompile group: ' Javax.servlet ', Name: ' Javax.servlet-api ', version: ' 3.1.0 '}
The relevant configuration of the data source is placed in: ldap.properties
sample.ldap.url=ldap://10.8.12.147:389
sample.ldap.userdn=cn=admin,dc=dianrong,dc=com
sample.ldap.password=123456
sample.ldap.base=dc=dianrong,dc=com
sample.ldap.clean=true
Read data source configuration file in Applicationcontext.xml, generate ldaptemplate
<?xml version= "1.0" encoding= "UTF-8"?> <beans xmlns= "Http://www.springframework.org/schema/beans" Xmlns:xs
I= "Http://www.w3.org/2001/XMLSchema-instance" xmlns:context= "Http://www.springframework.org/schema/context" xmlns:ldap= "Http://www.springframework.org/schema/ldap" xsi:schemalocation= "http://www.springframework.org/ Schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd Http://www.springfram Ework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http: Www.springframework.org/schema/ldap http://www.springframework.org/schema/ldap/spring-ldap.xsd "> < Context:property-placeholder location= "classpath:/ldap.properties"/> <ldap:context-source id= "ContextSource
"Password=" ${sample.ldap.password} "url=" ${sample.ldap.url} "
Username= "${sample.ldap.userdn}" Base= "${sample.ldap.base}"/> <ldap:ldap-template id= "Ldaptemplate" Context-source-ref = "Contextsource"/> <bean id= "Persondao" class= "Ldap.dao.odm.PersonDaoImpl" > <property name= "ldapte Mplate "ref=" ldaptemplate "/> </bean> <bean id=" Userdao "class=" Ldap.dao.UserDaoImpl "> < ;p roperty name= "ldaptemplate" ref= "ldaptemplate"/> </bean> </beans>
SPRINGMVC configuration file
<?xml version= "1.0" encoding= "UTF-8"?> <beans
xmlns= "Http://www.springframework.org/schema/beans"
xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance"
xmlns:context= "http://www.springframework.org/ Schema/context "
xmlns:mvc=" Http://www.springframework.org/schema/mvc "
xsi:schemalocation="/http/ Www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd/
http Www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
Http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd ">
<mvc:annotation-driven/>
<context:component-scan base-package= "Ldap.web"/>
<bean class= "Org.springframework.web.servlet.view.InternalResourceViewResolver" >
<property name= "prefix" Value= "/web-inf/jsp/"/>
<property name= "suffix" value= ". jsp"/>
</bean>
</beans >
Xml
<?xml version= "1.0" encoding= "UTF-8"?> <web-app id= "Tiink-preview" xmlns= "HTTP://JAVA.SUN.COM/XML/NS/J2EE" Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xsi:schemalocation= "Http://java.sun.com/xml/ns/j2ee http:/ /java.sun.com/xml/ns/j2ee/web-app_2_4.xsd "version=" 2.4 "> <display-name>spring LDAP Basic Example</ display-name> <listener> <listener-class> Org.springframework.web.context.ContextLoaderListener < ;/listener-class> </listener> <context-param> <param-name>contextconfiglocation</par
Am-name> <param-value>classpath:/applicationContext.xml</param-value> </context-param> <servlet> <servlet-name>basic</servlet-name> <servlet-class> Org.springframework.web.ser Vlet. Dispatcherservlet </servlet-class> <init-param> <param-name>contextconfiglocation</ Param-name> <param-value>/web-inf/basic-servlet.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet > <servlet-mapping> <servlet-name>basic</servlet-name> <url-pattern>/</url-pattern&
Gt </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </ Welcome-file-list> </web-app>
To this end, the following is an annotated way to implement object and directory mapping capabilities to simplify the code.
The model class writes like this:
Import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
Import org.springframework.ldap.odm.annotations.*;
Import Javax.naming.Name;
/** * Created by DRJR on 5/16/17. */@Entry (objectclasses = {"Person", "top"}) @JsonIgnoreProperties (value = {"DN"}) the public class person {@Id Priva
Te Name dn;
@Attribute (name = "cn") @DnAttribute (value = "cn", index = 0) private String fullName;
@Attribute (name = "SN") private String lastName;
@Attribute (name = "description") private String description;
@Transient Private String country;
@Transient Private String Company;
@Attribute (name = "telephonenumber") private String phone;
Public Name Getdn () {return DN;
} public void Setdn (Name dn) {this.dn = DN;
} public String GetDescription () {return description;
} public void SetDescription (String description) {this.description = description; } public StringGetfullname () {return fullName;
} public void Setfullname (String fullName) {this.fullname = FullName;
} public String Getlastname () {return lastName;
} public void Setlastname (String lastName) {this.lastname = LastName;
} public String Getcompany () {return company;
public void Setcompany (String company) {this.company = Company;
} public String Getcountry () {return country;
} public void Setcountry (String country) {this.country = country;
} public String Getphone () {return phone;
} public void Setphone (String phone) {this.phone = phone; }
}
@JsonIgnoreProperties This annotation is a class annotation that, when JSON is serialized, ignores some properties in the Java Bean, and both serialization and deserialization are affected. Without this annotation, the JSON conversion exception is reported.
@Id indicates the entity class DN, which must be of type javax.naming.Name, somewhat like the primary key meaning in a database table
@Attribute indicates that the directory attribute is mapped to an object class field, indicating that this is a property of objectclass
@Dnattribute labeled properties are part of the auto-build DN
@Entry annotations indicate that this is an LDAP entity mapping class
Interface implementation Class (The comparison of the above implementation class eliminates some code, more concise, do not need to manually map the field):
Import Ldap.dao.PersonDao;
Import Ldap.domain.Person;
Import Org.springframework.ldap.core.AttributesMapper;
Import Org.springframework.ldap.core.LdapTemplate;
Import Org.springframework.ldap.support.LdapNameBuilder;
Import javax.naming.NamingException;
Import javax.naming.directory.Attributes;
Import Javax.naming.ldap.LdapName;
Import java.util.List;
Import static org.springframework.ldap.query.LdapQueryBuilder.query;
/** * Created by DRJR on 5/16/17.
*/public class Persondaoimpl implements Persondao {private ldaptemplate ldaptemplate;
@Override public void Create (person person) {ldaptemplate.create (person);
} @Override public void update (person person) {ldaptemplate.update (person); } @Override public void Delete (person person) {Ldaptemplate.delete (Ldaptemplate.findbydn (BUILDDN (person).
Getfullname ()), Person.class)); } @Override Public list<string> getallpersonnames () {return LdaptemplAte.search (query (). attributes ("cn"). WHERE ("objectclass"). Is ("person"), New Attributesmapper<string> () {public String mapfromattributes (Attributes attrs
) throws Namingexception {return attrs.get ("cn"). Get (). toString ();
}
});
} @Override Public list<person> findAll () {return ldaptemplate.findall (Person.class);
} @Override Public Person Findbyprimarykey (String fullname) {ldapname DN = BUILDDN (fullname);
Person person = Ldaptemplate.findbydn (DN, person.class);
return person; Private LDAPName Builddn (String fullName) {return ldapnamebuilder.newinstance (). Add ("cn",
FullName). build ();
} public void Setldaptemplate (Ldaptemplate ldaptemplate) {this.ldaptemplate = ldaptemplate;
}
}