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:


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 classStudent {PrivateInteger ID; PrivateString name; PrivateString birthday;  PublicStudent () {} PublicStudent (Integer ID, string name, string birthday) { This. ID =ID;  This. Name =name;  This. Birthday =birthday; }     PublicInteger getId () {returnID; }     Public voidsetId (Integer id) { This. ID =ID; }     PublicString GetName () {returnname; }     Public voidsetName (String name) { This. Name =name; }     PublicString Getbirthday () {returnbirthday; }     Public voidsetbirthday (String birthday) { This. Birthday =birthday; }}

Package Com.lovo.infrastructure;import Java.util.arraylist;import Java.util.hashmap;import java.util.List;import  Java.util.map;import Com.lovo.domain.student;public class Studentrepository {private Map<integer, Student> Map =    New Hashmap<> ();        Public Studentrepository () {map.put (1001, New Student (1001, "Shanhao", "1980-11-28"));        Map.put (1002, New Student (1002, "King Sledgehammer", "1992-2-2"));    Map.put (1003, New Student (1003, "Zhang Sanfeng", "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);    } public Student FindByID (Integer ID) {return map.get (ID); } public list<student> FindAll () {return newArraylist<student> (Map.values ()); }}
Package Com.lovo.service;import Java.util.list;import Javax.ws.rs.consumes;import javax.ws.rs.delete;import Javax.ws.rs.get;import Javax.ws.rs.post;import Javax.ws.rs.put;import Javax.ws.rs.path;import Javax.ws.rs.pathparam;import Javax.ws.rs.produces;import Com.lovo.domain.student;import com.lovo.infrastructure.StudentRepository; @Path ("/service") @Produces ("Application/json") public class    Studentservice {private Studentrepository Studentrepo = new Studentrepository ();        @GET @Path ("/stu/{id}") @Consumes ("Application/json") public Student getstudent (@PathParam ("id") Integer ID) {    return Studentrepo.findbyid (ID);  @GET @Path ("/stu") @Consumes ("Application/json") public list<student> getallstudents () {return    Studentrepo.findall (); } @POST @Path ("/stu") @Consumes ("Application/json") public boolean addstudent (Student Student) {if (GE            Tstudent (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") Integ        ER 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.

Package Com.lovo;import Org.apache.cxf.jaxrs.jaxrsserverfactorybean;import Com.lovo.domain.student;import Com.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.