`
lvwenwen
  • 浏览: 933113 次
  • 性别: Icon_minigender_1
  • 来自: 魔都
社区版块
存档分类
最新评论

Spring整合CXF,发布RSETful 风格WebService

阅读更多
这篇文章是承接之前CXF整合Spring的这个项目示例的延伸,所以有很大一部分都是一样的。关于发布CXF WebServer和Spring整合CXF这里就不再多加赘述了。如果你对Spring整合CXF WebService不了解,具体你可以参看这两篇文章:
http://www.cnblogs.com/hoojo/archive/2011/03/30/1999563.html
http://www.cnblogs.com/hoojo/archive/2012/07/13/2590593.html
如果你不了解restful风格的WebService,你可以参考:
http://www.oracle.com/technetwork/articles/javase/index-137171.html
SpringMVC对RESTful的支持:
http://www.cnblogs.com/hoojo/archive/2011/06/10/2077422.html
使用 Jersey框架,搭建RESTful WebService(这个也比较简单)
http://www.ibm.com/developerworks/cn/web/wa-aj-tomcat/
官方文档:http://jersey.java.net/nonav/documentation/latest/user-guide.html#d4e8
其中,比较常用的RESTful框架就有Jersey、Spring REST、CXF RESTful,这些都可以很好的整合Spring框架,发布也相当的简单。且简单、易用、易上手,文档也比较丰富。

 

开发环境:
System:Windows
JavaEE Server:tomcat6
JavaSDK: jdk6+
IDE:eclipse、MyEclipse 6.6

开发依赖库:
JDK6、 JavaEE5、CXF-2.3.3、Spring 3.0.4

 

下面我们就接着http://www.cnblogs.com/hoojo/archive/2011/03/30/1999563.html这篇文章,开始我们CXF RESTful WebService的旅程,enjoy~!^_*

 

准备工作

首先,你需要添加相关的jar包

image

其中,jsr331-api-1.1.1.jar是必须的,利用CXF发布REST服务得用到它,在cxf的lib库中可以找到这个jar。

下载地址:http://www.apache.org/dyn/closer.cgi?path=/cxf/2.3.11/apache-cxf-2.3.11.zip

其它的jar包都是非必须的!

 

Java代码   收藏代码
  1. package com.hoo.entity;  
  2.    
  3. import java.util.Map;  
  4. import javax.xml.bind.annotation.XmlRootElement;  
  5.    
  6. /** 
  7.  * <b>function:</b> MapBean 封装Map集合元素 
  8.  * @author hoojo 
  9.  * @createDate 2012-7-20 下午01:22:31 
  10.  * @file MapBean.java 
  11.  * @package com.hoo.entity 
  12.  * @project CXFWebService 
  13.  * @blog http://blog.csdn.net/IBM_hoojo 
  14.  * @email hoojo_@126.com 
  15.  * @version 1.0 
  16.  */  
  17. @XmlRootElement  
  18. public class MapBean {  
  19.     private Map<String, User> map;  
  20.       
  21.     //@XmlElement(type = User.class)  
  22.     public Map<String, User> getMap() {  
  23.         return map;  
  24.     }  
  25.     public void setMap(Map<String, User> map) {  
  26.         this.map = map;  
  27.     }  
  28. }  
  29.    
  30.   
  31. package com.hoo.entity;  
  32.    
  33. import java.util.HashMap;  
  34. import java.util.List;  
  35. import javax.xml.bind.annotation.XmlRootElement;  
  36.    
  37. /** 
  38.  * <b>function:</b> Users Entity 
  39.  * @author hoojo 
  40.  * @createDate 2011-3-18 上午09:27:31 
  41.  * @file Users.java 
  42.  * @package com.hoo.entity 
  43.  * @project CXFWebService 
  44.  * @blog http://blog.csdn.net/IBM_hoojo 
  45.  * @email hoojo_@126.com 
  46.  * @version 1.0 
  47.  */  
  48. @XmlRootElement(name = "UserInfos")  
  49. public class Users {  
  50.     private List<User> users;  
  51.       
  52.     private User[] userArr;  
  53.       
  54.     private HashMap<String, User> maps;  
  55.       
  56.       
  57.    // getter/setter  
  58. }  
  59. package com.hoo.entity;  
  60.    
  61. import java.io.Serializable;  
  62. import javax.xml.bind.annotation.XmlRootElement;  
  63.    
  64. /** 
  65.  * <b>function:</b>User Entity 
  66.  * @author hoojo 
  67.  * @createDate Dec 16, 2010 10:20:02 PM 
  68.  * @file User.java 
  69.  * @package com.hoo.entity 
  70.  * @project AxisWebService 
  71.  * @blog http://blog.csdn.net/IBM_hoojo 
  72.  * @email hoojo_@126.com 
  73.  * @version 1.0 
  74.  */  
  75. @XmlRootElement(name = "UserInfo")  
  76. public class User implements Serializable {  
  77.     private static final long serialVersionUID = 677484458789332877L;  
  78.     private int id;  
  79.     private String name;  
  80.     private String email;  
  81.     private String address;  
  82.       
  83.     //getter/setter  
  84.       
  85.     @Override  
  86.     public String toString() {  
  87.         return this.id + "#" + this.name + "#" + this.email + "#" + this.address;  
  88.     }  
  89. }   
 

 

一、定义你的WebService的接口RESTSample.java,代码如下

 

Java代码   收藏代码
  1. package com.hoo.service;  
  2.    
  3. import java.io.IOException;  
  4. import javax.servlet.http.HttpServletRequest;  
  5. import javax.servlet.http.HttpServletResponse;  
  6. import javax.ws.rs.Consumes;  
  7. import javax.ws.rs.DELETE;  
  8. import javax.ws.rs.GET;  
  9. import javax.ws.rs.POST;  
  10. import javax.ws.rs.PUT;  
  11. import javax.ws.rs.Path;  
  12. import javax.ws.rs.PathParam;  
  13. import javax.ws.rs.Produces;  
  14. import javax.ws.rs.core.Context;  
  15. import javax.ws.rs.core.MediaType;  
  16.    
  17. import com.hoo.entity.MapBean;  
  18. import com.hoo.entity.User;  
  19. import com.hoo.entity.Users;  
  20.    
  21.    
  22. /* 
  23.      注释(Annotation):在 javax.ws.rs.* 中定义,是 JAX-RS (JSR 311) 规范的一部分。  
  24.     @Path:定义资源基 URI。由上下文根和主机名组成,资源标识符类似于 http://localhost:8080/RESTful/rest/hello。  
  25.     @GET:这意味着以下方法可以响应 HTTP GET 方法。  
  26.     @Produces:以纯文本方式定义响应内容 MIME 类型。 
  27.      
  28.     @Context: 使用该注释注入上下文对象,比如 Request、Response、UriInfo、ServletContext 等。  
  29.     @Path("{contact}"):这是 @Path 注释,与根路径 “/contacts” 结合形成子资源的 URI。  
  30.     @PathParam("contact"):该注释将参数注入方法参数的路径,在本例中就是联系人 id。其他可用的注释有 @FormParam、@QueryParam 等。  
  31.     @Produces:响应支持多个 MIME 类型。在本例和上一个示例中,APPLICATION/XML 将是默认的 MIME 类型。 
  32.  */  
  33. /** 
  34.  * <b>function:</b> CXF RESTful风格WebService 
  35.  * @author hoojo 
  36.  * @createDate 2012-7-20 下午01:23:04 
  37.  * @file RESTSampleSource.java 
  38.  * @package com.hoo.service 
  39.  * @project CXFWebService 
  40.  * @blog http://blog.csdn.net/IBM_hoojo 
  41.  * @email hoojo_@126.com 
  42.  * @version 1.0 
  43.  */  
  44. @Path(value = "/sample")  
  45. public interface RESTSample {  
  46.       
  47.     @GET  
  48.     @Produces(MediaType.TEXT_PLAIN)  
  49.     public String doGet();  
  50.       
  51.     @GET  
  52.     @Produces(MediaType.TEXT_PLAIN)  
  53.     @Path("/request/{param}")  
  54.     public String doRequest(@PathParam("param") String param,   
  55.             @Context HttpServletRequest servletRequest, @Context HttpServletResponse servletResponse);  
  56.       
  57.     @GET  
  58.     @Path("/bean/{id}")  
  59.     @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })  
  60.     public User getBean(@PathParam("id"int id);  
  61.       
  62.     @GET  
  63.     @Path("/list")  
  64.     @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })  
  65.     public Users getList();  
  66.       
  67.     @GET  
  68.     @Path("/map")  
  69.     @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })  
  70.     public MapBean getMap();  
  71.       
  72.     /* 
  73.         @Consumes:声明该方法使用 HTML FORM。  
  74.         @FormParam:注入该方法的 HTML 属性确定的表单输入。  
  75.         @Response.created(uri).build(): 构建新的 URI 用于新创建的联系人(/contacts/{id})并设置响应代码(201/created)。 
  76.         您可以使用 http://localhost:8080/Jersey/rest/contacts/<id> 访问新联系人 
  77.      */  
  78.     @POST  
  79.     @Path("/postData")  
  80.     public User postData(User user) throws IOException;  
  81.       
  82.     @PUT  
  83.     @Path("/putData/{id}")  
  84.     @Consumes(MediaType.APPLICATION_XML)  
  85.     public User putData(@PathParam("id"int id, User user);  
  86.       
  87.     @DELETE  
  88.     @Path("/removeData/{id}")  
  89.     public void deleteData(@PathParam("id"int id);  
  90. }  

 

二、RESTSample接口的实现,这里我们只是简单的实现下,并不是涉及实际的具体业务

 

Java代码   收藏代码
  1. package com.hoo.service;  
  2.    
  3. import java.io.IOException;  
  4. import java.util.ArrayList;  
  5. import java.util.HashMap;  
  6. import java.util.List;  
  7. import java.util.Map;  
  8. import javax.servlet.http.HttpServletRequest;  
  9. import javax.servlet.http.HttpServletResponse;  
  10. import javax.ws.rs.DELETE;  
  11. import javax.ws.rs.GET;  
  12. import javax.ws.rs.POST;  
  13. import javax.ws.rs.PUT;  
  14. import javax.ws.rs.Path;  
  15. import javax.ws.rs.PathParam;  
  16. import javax.ws.rs.Produces;  
  17. import javax.ws.rs.core.Context;  
  18. import javax.ws.rs.core.MediaType;  
  19. import javax.ws.rs.core.Request;  
  20. import javax.ws.rs.core.UriInfo;  
  21. import com.hoo.entity.MapBean;  
  22. import com.hoo.entity.User;  
  23. import com.hoo.entity.Users;  
  24.    
  25.    
  26. /* 
  27.      注释(Annotation):在 javax.ws.rs.* 中定义,是 JAX-RS (JSR 311) 规范的一部分。  
  28.     @Path:定义资源基 URI。由上下文根和主机名组成,资源标识符类似于 http://localhost:8080/RESTful/rest/hello。  
  29.     @GET:这意味着以下方法可以响应 HTTP GET 方法。  
  30.     @Produces:以纯文本方式定义响应内容 MIME 类型。 
  31.      
  32.     @Context: 使用该注释注入上下文对象,比如 Request、Response、UriInfo、ServletContext 等。  
  33.     @Path("{contact}"):这是 @Path 注释,与根路径 “/contacts” 结合形成子资源的 URI。  
  34.     @PathParam("contact"):该注释将参数注入方法参数的路径,在本例中就是联系人 id。其他可用的注释有 @FormParam、@QueryParam 等。  
  35.     @Produces:响应支持多个 MIME 类型。在本例和上一个示例中,APPLICATION/XML 将是默认的 MIME 类型。 
  36.  */  
  37. /** 
  38.  * <b>function:</b> CXF RESTful风格WebService 
  39.  * @author hoojo 
  40.  * @createDate 2012-7-20 下午01:23:04 
  41.  * @file RESTSampleSource.java 
  42.  * @package com.hoo.service 
  43.  * @project CXFWebService 
  44.  * @blog http://blog.csdn.net/IBM_hoojo 
  45.  * @email hoojo_@126.com 
  46.  * @version 1.0 
  47.  */  
  48. @Path(value = "/sample")  
  49. public class RESTSampleSource implements RESTSample {  
  50.       
  51.     @Context  
  52.     private UriInfo uriInfo;  
  53.       
  54.     @Context  
  55.     private Request request;  
  56.    
  57.       
  58.     @GET  
  59.     @Produces(MediaType.TEXT_PLAIN)  
  60.     public String doGet() {  
  61.         return "this is get rest request";  
  62.     }  
  63.       
  64.     @GET  
  65.     @Produces(MediaType.TEXT_PLAIN)  
  66.     @Path("/request/{param}")  
  67.     public String doRequest(@PathParam("param") String param,   
  68.             @Context HttpServletRequest servletRequest, @Context HttpServletResponse servletResponse) {  
  69.         System.out.println(servletRequest);  
  70.         System.out.println(servletResponse);  
  71.         System.out.println(servletRequest.getParameter("param"));  
  72.         System.out.println(servletRequest.getContentType());  
  73.         System.out.println(servletResponse.getCharacterEncoding());  
  74.         System.out.println(servletResponse.getContentType());  
  75.         return "success";  
  76.     }  
  77.       
  78.     @GET  
  79.     @Path("/bean/{id}")  
  80.     @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })  
  81.     public User getBean(@PathParam("id"int id) {  
  82.         System.out.println("####getBean#####");  
  83.         System.out.println("id:" + id);  
  84.         System.out.println("Method:" + request.getMethod());  
  85.         System.out.println("uri:" + uriInfo.getPath());  
  86.         System.out.println(uriInfo.getPathParameters());  
  87.           
  88.         User user = new User();  
  89.         user.setId(id);  
  90.         user.setName("JojO");  
  91.         return user;  
  92.     }  
  93.       
  94.     @GET  
  95.     @Path("/list")  
  96.     @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })  
  97.     public Users getList() {  
  98.         System.out.println("####getList#####");  
  99.         System.out.println("Method:" + request.getMethod());  
  100.         System.out.println("uri:" + uriInfo.getPath());  
  101.         System.out.println(uriInfo.getPathParameters());  
  102.           
  103.         List<User> list = new ArrayList<User>();  
  104.         User user = null;  
  105.         for (int i = 0; i < 4;i ++) {  
  106.             user = new User();  
  107.             user.setId(i);  
  108.             user.setName("JojO-" + i);  
  109.             list.add(user);  
  110.         }  
  111.         Users users = new Users();  
  112.         users.setUsers(list);  
  113.         return users;  
  114.     }  
  115.       
  116.     @GET  
  117.     @Path("/map")  
  118.     @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })  
  119.     public MapBean getMap() {  
  120.         System.out.println("####getMap#####");  
  121.         System.out.println("Method:" + request.getMethod());  
  122.         System.out.println("uri:" + uriInfo.getPath());  
  123.         System.out.println(uriInfo.getPathParameters());  
  124.           
  125.         Map<String, User> map = new HashMap<String, User>();  
  126.         User user = null;  
  127.         for (int i = 0; i < 4;i ++) {  
  128.             user = new User();  
  129.             user.setId(i);  
  130.             user.setName("JojO-" + i);  
  131.             map.put("key-" + i, user);  
  132.         }  
  133.         MapBean bean = new MapBean();  
  134.         bean.setMap(map);  
  135.         return bean;  
  136.     }      
  137.       
  138.     /* 
  139.         @Consumes:声明该方法使用 HTML FORM。  
  140.         @FormParam:注入该方法的 HTML 属性确定的表单输入。  
  141.         @Response.created(uri).build(): 构建新的 URI 用于新创建的联系人(/contacts/{id})并设置响应代码(201/created)。 
  142.         您可以使用 http://localhost:8080/Jersey/rest/contacts/<id> 访问新联系人 
  143.      */  
  144.     @POST  
  145.     @Path("/postData")  
  146.     @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })  
  147.     public User postData(User user) throws IOException {  
  148.         System.out.println(user);  
  149.         user.setName("jojo##12321321");  
  150.         return user;  
  151.     }   
  152.       
  153.     @PUT  
  154.     @Path("/putData/{id}")  
  155.     @Produces({ MediaType.APPLICATION_XML })  
  156.     public User putData(@PathParam("id"int id, User user) {  
  157.         System.out.println("#####putData#####");  
  158.         System.out.println(user);  
  159.         user.setId(id);  
  160.         user.setAddress("hoojo#gz");  
  161.         user.setEmail("hoojo_@126.com");  
  162.         user.setName("hoojo");  
  163.         System.out.println(user);  
  164.         return user;  
  165.     }  
  166.       
  167.     @DELETE  
  168.     @Path("/removeData/{id}")  
  169.     public void deleteData(@PathParam("id"int id) {  
  170.         System.out.println("#######deleteData#######" + id);  
  171.     }  
  172. }  

 

三、配置我们的WebService,修改applicationContext-server.xml。这里主要是添加jaxrs标签的支持,修改头部文件如下:

 

Xml代码   收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:context="http://www.springframework.org/schema/context"  
  4.     xmlns:jaxws="http://cxf.apache.org/jaxws"  
  5.     xmlns:jaxrs="http://cxf.apache.org/jaxrs"  
  6.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  7.     xsi:schemaLocation="http://www.springframework.org/schema/beans   
  8.     http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
  9.     http://www.springframework.org/schema/context  
  10.     http://www.springframework.org/schema/context/spring-context-3.0.xsd  
  11.     http://cxf.apache.org/jaxws   
  12.     http://cxf.apache.org/schemas/jaxws.xsd  
  13.     http://cxf.apache.org/jaxrs  
  14.     http://cxf.apache.org/schemas/jaxrs.xsd">  

 特别注意上面加粗带下划线的部分,这是新增加的配置。我们发布restful WebService需要用到它。

 

然后在配置文件中添加如下配置

 

Xml代码   收藏代码
  1. <import resource="classpath:META-INF/cxf/cxf.xml"/>  
  2. <import resource="classpath:META-INF/cxf/cxf-extension-soap.xml"/>  
  3. <import resource="classpath:META-INF/cxf/cxf-servlet.xml"/>  
  4. <bean id="restSample" class="com.hoo.service.RESTSampleSource"/>  
  5. <!-- 这里的地址很重要,客户端需要通过这个地址来访问WebService -->  
  6. <jaxrs:server id="restServiceContainer" address="/rest">  
  7.     <jaxrs:serviceBeans>  
  8.         <ref bean="restSample" />  
  9.     </jaxrs:serviceBeans>  
  10.     <jaxrs:extensionMappings>  
  11.         <entry key="json" value="application/json" />  
  12.         <entry key="xml" value="application/xml" />  
  13.     </jaxrs:extensionMappings>  
  14.     <jaxrs:languageMappings>  
  15.            <entry key="en" value="en-gb"/>    
  16.     </jaxrs:languageMappings>  
  17. </jaxrs:server>  

这样服务器端就完成了CXF RESTful WebService的发布,启动你的tomcat。然后在浏览器中服务地址:http://localhost:8000/CXFWebService/ (其实这里请求的是CXFServlet,你可以看看上一篇Spring整合CXF文章的web.xml的配置)

你就可以看到我们这里刚刚发布的RESTSample rest的WebService

image 

你也可以看看里面的xml,也就是WebService的wsdl文件内容。我们找一个GET方式的WebService的方法,在浏览器中调用一下试试

http://localhost:8000/CXFWebService/rest/sample/bean/123

这个url对应到下面这个方法

Java代码  收藏代码
  1. @GET  
  2. @Path("/bean/{id}")  
  3. @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })  
  4. public User getBean(@PathParam("id"int id)  
 

结果如下

image

一篇xml文档内容。

 

四、编写客户端代码,调用RESTful WebService

 

Java代码   收藏代码
  1. package com.hoo.client;  
  2.    
  3. import java.io.IOException;  
  4. import javax.ws.rs.core.MediaType;  
  5. import org.apache.cxf.jaxrs.client.WebClient;  
  6. import org.junit.After;  
  7. import org.junit.Before;  
  8. import org.junit.Test;  
  9. import org.springframework.context.ApplicationContext;  
  10. import org.springframework.context.support.ClassPathXmlApplicationContext;  
  11. import com.hoo.entity.MapBean;  
  12. import com.hoo.entity.User;  
  13. import com.hoo.entity.Users;  
  14. import com.hoo.service.RESTSample;  
  15.    
  16. /** 
  17.  * <b>function:</b> RESTful风格WebService 
  18.  * @author hoojo 
  19.  * @createDate 2012-7-20 下午03:31:03 
  20.  * @file RSETServiceClient.java 
  21.  * @package com.hoo.client 
  22.  * @project CXFWebService 
  23.  * @blog http://blog.csdn.net/IBM_hoojo 
  24.  * @email hoojo_@126.com 
  25.  * @version 1.0 
  26.  */  
  27. public class RSETServiceClient {  
  28.    
  29.     private static WebClient client;  
  30.       
  31.     @Before  
  32.     public void init() {  
  33.         // 手动创建webClient对象,注意这里的地址是发布的那个/rest地址  
  34.         //String url = "http://localhost:8000/CXFWebService/rest/";  
  35.         //client = WebClient.create(url);  
  36.    
  37.         // 从Spring Ioc容器中拿webClient对象  
  38.         ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext-client.xml");  
  39.         client = ctx.getBean("webClient", WebClient.class);  
  40.     }  
  41.       
  42.     @After  
  43.     public void destory(){  
  44.     }  
  45.       
  46.     @Test  
  47.     public void testGet() {  
  48.         System.out.println(client.path("sample").accept(MediaType.TEXT_PLAIN).get(String.class));  
  49.     }  
  50.       
  51.     @Test  
  52.     public void testRequest() {  
  53.         System.out.println(client.path("sample/request/234234").accept(MediaType.TEXT_PLAIN).get(String.class));  
  54.     }  
  55.       
  56.     @Test  
  57.     public void testBean() {  
  58.         User user = client.path("sample/bean/{id}"25).accept(MediaType.APPLICATION_XML).get(User.class);  
  59.         System.out.println(user);  
  60.     }  
  61.       
  62.     @Test  
  63.     public void testList() {  
  64.         System.out.println(client.path("sample/list").accept(MediaType.APPLICATION_XML).get(Users.class).getUsers());  
  65.     }  
  66.       
  67.     @Test  
  68.     public void testMap() {  
  69.         System.out.println(client.path("sample/map").accept(MediaType.APPLICATION_XML).get(MapBean.class).getMap());  
  70.     }  
  71.       
  72.     @Test  
  73.     public void testDeleteData() {  
  74.         client.path("sample/removeData/23").delete();  
  75.     }  
  76.       
  77.     @Test  
  78.     public void testPostData() {  
  79.         User user = new User();  
  80.         user.setId(21432134);  
  81.         user.setAddress("hoojo#gz");  
  82.         user.setEmail("hoojo_@126.com");  
  83.         user.setName("hoojo");  
  84.         System.out.println(client.path("sample/postData").accept(MediaType.APPLICATION_XML).post(user, User.class));  
  85.     }  
  86.       
  87.     @Test  
  88.     public void testPutData() {  
  89.         User user = new User();  
  90.         user.setId(21432134);  
  91.         System.out.println(client.path("sample/putData/1").accept(MediaType.APPLICATION_XML).put(user).getEntity());  
  92.     }  
  93. }  

如果你喜欢用Spring的方式,还需要在applicationContext-client.xml中增加如下配置

Xml代码   收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:context="http://www.springframework.org/schema/context"  
  4.     xmlns:jaxws="http://cxf.apache.org/jaxws"  
  5.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  6.     xsi:schemaLocation="http://www.springframework.org/schema/beans   
  7.     http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
  8.     http://www.springframework.org/schema/context  
  9.     http://www.springframework.org/schema/context/spring-context-3.0.xsd  
  10.     http://cxf.apache.org/jaxws   
  11.     http://cxf.apache.org/schemas/jaxws.xsd">  
  12.       
  13.     <bean id="webClient" class="org.apache.cxf.jaxrs.client.WebClient" factory-method="create">  
  14.         <constructor-arg type="java.lang.String" value="http://localhost:8000/CXFWebService/rest/" />  
  15.     </bean>  
  16.       
  17. </beans>  

这种是利用WebClient对象来调用WebService,还有一种方法也可以调用WebService,代码如下:

 // 手动创建

Java代码   收藏代码
  1. //RESTSample sample = JAXRSClientFactory.create("http://localhost:8000/CXFWebService/rest", RESTSample.class);  
  2.    
  3. // 从Spring Ioc容器中拿webClient对象  
  4. ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext-client.xml");  
  5. RESTSample sample = ctx.getBean("restSampleBean", RESTSample.class);  
  6.    
  7. System.out.println(sample);  
  8.    
  9. System.out.println(sample.doGet());  
  10. //System.out.println(sample.doRequest("haha", null, null));  
  11. System.out.println(sample.getBean(22));  
  12. System.out.println(sample.getList());  
  13. System.out.println(sample.getMap().getMap());  
  14. User user = new User();  
  15. user.setId(21432134);  
  16. user.setAddress("hoojo#gz");  
  17. user.setEmail("hoojo_@126.com");  
  18. user.setName("hoojo");  
  19. System.out.println(sample.postData(user));  
  20. System.out.println(sample.putData(111, user));  
  21. sample.deleteData(2);  

这种方式相对比WebClient要简单,直接使用接口中的方法即可。同样如果你要整合到Spring可以在applicationContext-client.xml中增加配置如下:

Xml代码   收藏代码
  1. <bean id="restSampleBean" class="org.apache.cxf.jaxrs.client.JAXRSClientFactory" factory-method="create">  
  2.     <constructor-arg type="java.lang.String" value="http://localhost:8000/CXFWebService/rest/" />  
  3.     <constructor-arg type="java.lang.Class" value="com.hoo.service.RESTSample" />  
  4. </bean>  

执行以上方法可以看到控制台打印结果如下:

 

 写道
client console
org.apache.cxf.jaxrs.client.ClientProxyImpl@1cf7491
this is get rest request
22#JojO#null#null
com.hoo.entity.Users@16eb6bc
{key-0=0#JojO-0#null#null, key-1=1#JojO-1#null#null, key-2=2#JojO-2#null#null, key-3=3#JojO-3#null#null}
21432134#jojo##12321321#hoojo_@126.com#hoojo#gz
111#hoojo#hoojo_@126.com#hoojo#gz

server console
####getBean#####
id:22
Method:GET
uri:sample/bean/22
{id=[22]}
####getList#####
Method:GET
uri:sample/list
{}
####getMap#####
Method:GET
uri:sample/map
{}
21432134#hoojo#hoojo_@126.com#hoojo#gz
#####putData#####
21432134#hoojo#hoojo_@126.com#hoojo#gz
111#hoojo#hoojo_@126.com#hoojo#gz
#######deleteData#######2

就这样,整合restful WebService成功。

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics