开发RESTful WebService
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.xsdhttp://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>client
所需jar包
由于RESTful就是利用最原始的http協議數據傳輸。所以client事實上就是一個httpclient。有下面幾種實現方式
?
JAX-RS Client API--cxf3.0+
Proxy【使用起來簡單。代理封裝通信細節】
Apache HttpClient
WebClient
?
為了簡單我使用了Proxy方式
代碼例如以下
public class MyClient {/** @MethodName : main* @Description : JaxRs測試client* @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特性。
總結
以上是生活随笔為你收集整理的开发RESTful WebService的全部內容,希望文章能夠幫你解決所遇到的問題。
                            
                        - 上一篇: Hal.dll是什么
 - 下一篇: 在word文档中如何修改字体