如何封裝RESTful Web Service

  所謂Web Service是一個平臺獨立的,低耦合的,自包含的、可編程的Web應用程序,有了Web Service異構系統之間就能夠經過XML或JSON來交換數據,這樣就能夠用於開發分佈式的互操做的應用程序。Web Service使得運行在不一樣機器上的不一樣應用無須藉助附加的、專門的第三方軟件或硬件就可相互交換數據或集成,不管它們各自所使用的語言、平臺或內部協議是什麼,均可以相互交換數據。Web Service爲整個企業甚至多個組織之間的業務流程的集成提供了一個通用機制。html


  REST(REpresentational State Transfer)是Roy Fielding博士於2000年在他的博士論文中提出來的一種軟件架構風格。它是一種針對網絡應用的設計和開發方式,能夠下降開發的複雜性,提升系統的可伸縮性。近年來,愈來愈多的Web Service開始採用REST風格設計和實現。例如,亞馬遜提供接近REST風格的Web Service進行圖書查找;雅虎提供的Web Service也是REST風格的。java

這裏寫圖片描述

這裏寫圖片描述

 

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

  這裏要講的是基於Apache CXF來建立RESTful Web Service。能夠在Apache的網站下載到CXF的發行版本。Apache的官網是這樣介紹CXF的:spring

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程序了。話很少說,直接上代碼。apache

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
這裏寫圖片描述json

http://localhost:9999/service/stu
這裏寫圖片描述瀏覽器

相關文章
相關標籤/搜索