How to encapsulate a restful Web Service

Source: Internet
Author: User
Tags representational state transfer

?? The so-called Web service is a platform-independent, low-coupling, self-contained, programmable Web application with Web service heterogeneous systems that can exchange data through XML or JSON, which can be used to develop distributed interoperable applications. WEB service enables different applications running on different machines to exchange data or integrations without the use of additional, specialized third-party software or hardware, regardless of the language, platform, or internal protocol in which they are used, to exchange data with each other. WEB Service provides a common mechanism for integration of business processes across the enterprise and even across multiple organizations.
?? REST (representational state Transfer) is a software architecture style proposed by Dr. Roy Fielding in his doctoral dissertation in 2000. It is a design and development method for network application, which can reduce the complexity of development and increase the scalability of the system. In recent years, more and more Web service has been designed and implemented in restful style. For example, Amazon provides a close-to-rest-style Web service for book searches, and the Web service provided by Yahoo is restful.




?? If you want to have a deeper understanding of rest and a deeper understanding, we recommend that you read an article in Infoq, "Understanding the true Rest architecture style." I believe that many people who think they know rest are not aware of what is real rest until after reading this article. There is a very good article in the IBM developer community called "Creating restful web Services with spring three" to explain how to use Spring Web and spring MVC to create a restful web Service. As this article has been very well done, I will not dwell on the contents of it here.

?? This is about creating a restful Web Service based on the Apache CXF. can be downloaded to CXF's release version on Apache's website. Apache's official website is the introduction of CXF:

Apache CXF is an open Source services framework. CXF helps you build and develop services using frontend programming APIs, like Jax-WS and Jax-rs. These services can speak a variety of protocols such as SOAP, Xml/http, RESTful HTTP, or CORBA and work over a variety of Transports such as HTTP, JMS or JBI.

?? After the download is done, unzip and find the Lib directory, add the jar file to your Java project, and you can start writing your Web service. Words don't say much, directly on the code.

 PackageCom.lovo.domain;ImportJavax.xml.bind.annotation.XmlRootElement;@XmlRootElement(name ="Student") Public  class Student {      PrivateInteger ID;PrivateString name;PrivateString birthday; Public Student() {    } Public Student(Integer ID, string name, string birthday) { This. id = ID; This. name = name; This. Birthday = Birthday; } PublicIntegergetId() {returnId } Public void setId(Integer ID) { This. id = ID; } PublicStringGetName() {returnName } Public void SetName(String name) { This. name = name; } PublicStringGetbirthday() {returnBirthday } Public void Setbirthday(String birthday) { This. Birthday = Birthday; }}
 PackageCom.lovo.infrastructure;ImportJava.util.ArrayList;ImportJava.util.HashMap;ImportJava.util.List;ImportJava.util.Map;ImportCom.lovo.domain.Student; Public  class studentrepository {    PrivateMap<integer, student> map =NewHashmap<> (); Public studentrepository() {Map.put (1001,NewStudent (1001,"Shanhao","1980-11-28")); Map.put (1002,NewStudent (1002,"King Sledgehammer","1992-2-2")); Map.put (1003,NewStudent (1003,"Zhang San Feng","1930-3-3")); } Public void Save(Student Student) {if(Student! =NULL) {Map.put (Student.getid (), student); }    } Public void Delete(Student Student) {if(Student! =NULL&& Map.containskey (Student.getid ())) {Map.Remove (Student.getid ()); }    } Public void Update(Student Student)        {Delete (student);    Save (student); } PublicStudentFindByID(Integer ID) {returnMap.get (ID); } PublicList<student>FindAll() {return NewArraylist<student> (Map.values ()); }}
 PackageCom.lovo.service;ImportJava.util.List;ImportJavax.ws.rs.Consumes;ImportJavax.ws.rs.DELETE;ImportJavax.ws.rs.GET;ImportJavax.ws.rs.POST;ImportJavax.ws.rs.PUT;ImportJavax.ws.rs.Path;ImportJavax.ws.rs.PathParam;ImportJavax.ws.rs.Produces;ImportCom.lovo.domain.Student;ImportCom.lovo.infrastructure.StudentRepository;@Path("/service")@Produces("Application/json") Public  class studentservice {    PrivateStudentrepository Studentrepo =NewStudentrepository ();@GET    @Path("/stu/{id}")@Consumes("Application/json") PublicStudentgetstudent(@Pathparam("id") Integer ID) {returnStudentrepo.findbyid (ID); }@GET    @Path("/stu")@Consumes("Application/json") PublicList<student>getallstudents() {returnStudentrepo.findall (); }@POST    @Path("/stu")@Consumes("Application/json") Public Boolean addstudent(Student Student) {if(Getstudent (Student.getid ()) = =NULL) {Studentrepo.save (student);return true; }return false; }@PUT    @Path("/stu/{id}")@Consumes("Application/json") Public Boolean updatestudent(@Pathparam("id") Integer ID, Student Student) {if(Getstudent (id)! =NULL) {studentrepo.update (student);return true; }return false; }@DELETE    @Path("/stu/{id}")@Consumes("Application/json") Public Boolean deletestudent(@Pathparam("id") Integer ID) {Student Student = getstudent (ID);if(Student! =NULL) {Studentrepo.delete (student);return true; }return false; }}

?? Finally, start the server for the Web service and test it.

Packagecom. Lovo;import org. Apache. CXF. Jaxrs. Jaxrsserverfactorybean;Importcom. Lovo. Domain. Student;Importcom. Lovo. Service. Studentservice;public class Myrestserver {public static void main (string[] args) {Jaxrsserverfactorybean myrestfulserver = New Jaxrsserverfactorybean ();Myrestfulserver. Setresourceclasses(Student. Class); Myrestfulserver. Setservicebean(New Studentservice ());Myrestfulserver. Setaddress("http://localhost:9999/"); Myrestfulserver. Create(); }  }

?? Enter the following two URIs in the browser to see the results:
http://localhost:9999/service/stu/1002

Http://localhost:9999/service/stu

How to encapsulate a restful Web Service

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.