如何封裝RESTful Web Service

來源:互聯網
上載者:User

標籤:html   基於   list   網站   color   spring   factor   ica   附加   

  所謂Web Service是一個平台獨立的,低耦合的,自包含的、可程式化的Web應用程式,有了Web Service異構系統之間就可以通過XML或JSON來交換資料,這樣就可以用於開發分布式的互操作的應用程式。Web Service使得運行在不同機器上的不同應用無須藉助附加的、專門的第三方軟體或硬體就可相互交換資料或整合,無論它們各自所使用的語言、平台或內部協議是什麼,都可以相互交換資料。Web Service為整個企業甚至多個組織之間的商務程序的整合提供了一個通用機制。


??REST(REpresentational State Transfer)是Roy Fielding博士於2000年在他的博士論文中提出來的一種軟體架構風格。它是一種針對網路應用的設計和開發方式,可以降低開發的複雜性,提高系統的延展性。近年來,越來越多的Web Service開始採用REST風格設計和實現。例如,亞馬遜提供接近REST風格的Web Service進行圖書尋找;雅虎提供的Web Service也是REST風格的。

 

如果要對REST有更深入的瞭解和更深刻的認識,推薦大家閱讀InfoQ上面的一篇文章《理解本真的REST架構風格》。相信很多自以為懂REST的人看完這篇文章之後才知道什麼是真正的REST。在IBM的開發人員社區中有一篇非常好的文章,名為《使用Spring 3來建立RESTful Web Services》,講解如何用spring Web和Spring MVC來建立REST風格的Web Service。由於這篇文章已經講得很好了,這裡我就不再贅述其中的內容。

??這裡要講的是基於Apache CXF來建立RESTful Web Service。可以在Apache的網站下載到CXF的發行版本。Apache的官網是這樣介紹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.

 

下載完成後解壓並找到lib目錄,將其中的jar檔案添加你的Java項目中,接下來就可以開始編寫你的Web Service程式了。話不多說,直接上代碼。

package com.lovo.domain;import javax.xml.bind.annotation.XmlRootElement;@XmlRootElement(name = "Student")public class Student {      private Integer id;    private String name;    private String birthday;    public Student() {    }    public Student(Integer id, String name, String birthday) {        this.id = id;        this.name = name;        this.birthday = birthday;    }    public Integer getId() {        return id;    }    public void setId(Integer id) {        this.id = id;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public String getBirthday() {        return birthday;    }    public void setBirthday(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, "駱昊", "1980-11-28"));        map.put(1002, new Student(1002, "王大鎚", "1992-2-2"));        map.put(1003, new Student(1003, "張三丰", "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 new ArrayList<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 (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;    }}

 

最後來啟動Web Service的伺服器並進行測試。

 

 

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();      }  } 

 

在瀏覽器中分別輸入以下兩個URI查看結果:
http://localhost:9999/service/stu/1002

http://localhost:9999/service/stu

 

如何封裝RESTful Web Service

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.