開發RESTful WebService

來源:互聯網
上載者:User

標籤:des   style   blog   http   java   使用   os   檔案   

RESTful風格的webservice越來越流行了,sun也推出了RESTful WebService的官方規範:JAX-RS,全稱:Java API for RESTful WebService。該規範定義了一系列的註解

 

RESTful簡化了web service的設計,它不再需要wsdl,也不再需要soap協議,而是通過最簡單的http協議傳輸資料(包括xml或json)。既簡化了設計,也減少了網路傳輸量(因為只傳輸代表資料的xml或json,沒有額外的xml封裝)

 

下面為大家介紹使用cxf開發RESTful WebService

 

Cxf2.7實現了大部分的jax-rs規範,從cxf3.0開始實現jax-rs的全套規範

 

服務端


Spring3+cxf開發RESTfulweb service

 


服務端jar包


上面的jettison jar包是用來將jaxb擴充為為json支援的jar

 

實體類

package com.tgb.cxf.server;import javax.xml.bind.annotation.XmlRootElement;//一定要使用XmlRootElement註解進行標註@XmlRootElement(name="user")public class User {private String id;private String name;public String getId() {return id;}public void setId(String id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}}

WebService介面

@Path("/userservice/")public interface IMyService {@Path("/addUser/")@POSTResponse addUser(User user);@Path("/delUser/{id}/")@DELETEResponse delUser(@PathParam("id") String id);@Path("/updateUser/")@PUTResponse updateUser(User user);@Path("/getUserById/{id}/")@GET@Produces("application/json")//返回json資料格式User getUserById(@PathParam("id") String id);@Path("/")@GET@Produces("application/json")//返回json資料格式List<User> findAllUsers();}

WebService實作類別

public class MyServiceImpl implements IMyService {private HashMap<String, User> users = new HashMap<String,User>();public MyServiceImpl(){init();}public Response addUser(User user) {users.put(user.getId(), user);System.out.println("添加使用者成功");System.out.println(users.size());System.out.println(users.get("2").getName());return Response.ok().build();}public Response delUser(String id) {users.remove(id);System.out.println(users.size());return Response.ok().build();}public Response updateUser(User user) {users.put(user.getId(), user);System.out.println(users.get("1").getName());return Response.ok().build();}public User getUserById(String id) {return users.get(id);}private void init(){User user = new User();user.setId("1");user.setName("溫歡");users.put(user.getId(), user);}public List<User> findAllUsers() {List<User> userlist = new ArrayList<User>();userlist.add(users.get("1"));return userlist;}}

spring-cxf.xml設定檔

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jaxrs="http://cxf.apache.org/jaxrs"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd"><!-- 注意這裡的jaxrs命名空間需要大家手動添加 --><!-- 發布webservice --><bean id="serviceBean" class="com.tgb.cxf.server.MyServiceImpl"/><jaxrs:server id="userService"  address="/myservice"><jaxrs:serviceBeans><ref bean="serviceBean"/></jaxrs:serviceBeans></jaxrs:server></beans>

web.xml檔案配置

<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">    <!-- 配置spring -->  <context-param><param-name>contextConfigLocation</param-name><param-value>classpath:config/spring-cxf.xml</param-value>  </context-param>    <listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  </listener>    <!-- 配置cxf servlet -->  <servlet>        <servlet-name>cxf</servlet-name>        <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>        <load-on-startup>1</load-on-startup>    </servlet>    <servlet-mapping>        <servlet-name>cxf</servlet-name>        <url-pattern>/services/*</url-pattern>    </servlet-mapping></web-app>


用戶端

所需jar包



因為RESTful就是利用最原始的http協議傳輸資料,所以用戶端其實就是一個http用戶端,有以下幾種實現方式

 

JAX-RS Client API--cxf3.0+

Proxy【使用起來簡單,代理封裝通訊細節】

Apache HttpClient

WebClient

 

為了簡單我使用了Proxy方式

代碼如下

public class MyClient {/** @MethodName: main * @Description: JaxRs測試用戶端 * @param args */public static void main(String[] args) {IMyService myService = JAXRSClientFactory.create("http://localhost:8096/cxf02/services/myservice",IMyService.class);User user = myService.getUserById("1");System.out.println(user.getName());User user = new User();user.setId("2");user.setName("委座");myService.addUser(user);/*User user = new User();user.setId("1");user.setName("123");myService.updateUser(user);*/myService.delUser("1");System.out.println(myService.findAllUsers().get(0).getName());}}

大家可以使用TCPMON這個工具監控以下,可以看到http body中只是簡單的json串,沒有像soap協議那樣的“信封”封裝

 

使用RESTful設計風格+傳輸json資料格式可以大大的簡化web service的設計並提高傳輸效率


其實springMVC也採用了RESTful的設計風格,不過它使用的是spring自己的註解,這些註解和jax-rs中的註解驚奇的類似。如果大家有興趣可以研究一下springMVC的RESTful特性。


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.