1. 程式人生 > >CXF 發布rest服務

CXF 發布rest服務

service log source media 應用 ebs jaxrs 2.3 http

1.1 什麽是rest服務

REST 是一種軟件架構模式,只是一種風格,rest服務采用HTTP 做傳輸協議,REST 對於HTTP 的利用實現精確的資源定位。

Rest要求對資源定位更加準確,如下:

非rest方式:http://ip:port/queryUser.action?userType=student&id=001

Rest方式:http://ip:port/user/student/query/001

Rest方式表示互聯網上的資源更加準確,但是也有缺點,可能目錄的層級較多不容易理解。

REST 是一種軟件架構理念,現在被移植到Web 服務上,那麽在開發Web 服務上,偏於面向資源的服務適用於REST,REST 簡單易用,效率高,SOAP 成熟度較高,安全性較好。

註意:REST 不等於WebService,JAX-RS 只是將REST 設計風格應用到Web 服務開發上。

1.2 發布rest服務

1.2.1 需求:

發布查詢學生信息的服務,以json和xml數據格式返回。

1.2.2 pojo

@XmlRootElement(name="student")

public class Student {

private long id;

private String name;

private Date birthday;

1.2.3 SEI

@WebService

@Path("/student")

public interface StudentService {

@GET

@Produces(MediaType.APPLICATION_XML)

@Path("/query/{id}")

public Student queryStudent(@PathParam("id")long id)throws Exception;

@GET

@Produces({"application/json;charset=utf-8",MediaType.APPLICATION_XML})

@Path("/querylist/{id}")

public

List<Student> queryStudentList(@PathParam("id")long id)throws Exception;

}

上邊代碼中:

queryStudent方法以xml格式發布

queryStudentList方法以json和xml兩種格式發布。

1.2.4 SEI實現類

public class StudentServiceImpl implements StudentService {

@Override

public Student queryStudent(long id) throws Exception {

Student student = new Student();

student.setId(100000l);

student.setName("張三");

student.setBirthday(new Date());

return student;

}

@Override

public List<Student> queryStudentList(long id) throws Exception {

Student student1 = new Student();

student1.setId(100000l);

student1.setName("李四");

student1.setBirthday(new Date());

Student student2 = new Student();

student2.setId(100000l);

student2.setName("張三");

student2.setBirthday(new Date());

List<Student> list = new ArrayList<Student>();

list.add(student1);

list.add(student2);

return list;

}

}

1.2.5 程序代碼發布

public class RestServer {

public static void main(String[] args) {

JAXRSServerFactoryBean jaxrsServerFactoryBean = new JAXRSServerFactoryBean();

//rest地址

jaxrsServerFactoryBean.setAddress("http://127.0.0.1:12345/rest");

//設置SEI實現類

jaxrsServerFactoryBean.setResourceClasses(StudentServiceImpl.class);

jaxrsServerFactoryBean.create();

}

}

1.2.6 Spring配置文件發布

<!-- rest服務發布 -->

<jaxrs:server address="/rest">

<jaxrs:serviceBeans>

<bean class="cn.itcast.ws.cxf.rest.server.StudentServiceImpl"/>

</jaxrs:serviceBeans>

1.2.7 測試

queryStudent方法測試:

http://127.0.0.1:8080/工程名/ws/rest/student/query/1

queryStudentList方法測試:

返回json

http://127.0.0.1:8080/工程名/ws/rest/student/querylist/1?_type=json

返回xml

http://127.0.0.1:8080/工程名/ws/rest/student/querylist/1?_type=xml

CXF 發布rest服務