Spring整合CXF webservice restful 实例

来源:互联网 发布:韩国网络电视直播 编辑:程序博客网 时间:2024/05/19 23:00

webservice restful接口跟soap协议的接口实现大同小异,只是在提供服务的类/接口的注解上存在差异,具体看下面的代码,然后自己对比下就可以了。

用到的基础类

User.java

 

[源码]
  1.  @XmlRootElement(name="User")  
  2.  public class User {  
  3.    
  4.      private String userName;  
  5.      private String sex;  
  6.      private int age;  
  7.        
  8.      public User(String userName, String sex, int age) {  
  9.          super();  
  10.          this.userName = userName;  
  11.          this.sex = sex;  
  12.          this.age = age;  
  13.      }  
  14.        
  15.      public User() {  
  16.          super();  
  17.      }  
  18.    
  19.      public String getUserName() {  
  20.          return userName;  
  21.      }  
  22.      public void setUserName(String userName) {  
  23.          this.userName = userName;  
  24.      }  
  25.      public String getSex() {  
  26.          return sex;  
  27.      }  
  28.      public void setSex(String sex) {  
  29.          this.sex = sex;  
  30.      }  
  31.      public int getAge() {  
  32.          return age;  
  33.      }  
  34.      public void setAge(int age) {  
  35.          this.age = age;  
  36.      }  
  37.        
  38.      public static void main(String[] args) throws IOException {  
  39.          System.setProperty("http.proxySet""true");   
  40.    
  41.          System.setProperty("http.proxyHost",  "192.168.1.20");   
  42.    
  43.          System.setProperty("http.proxyPort""8080");  
  44.            
  45.          URL url = new URL("http://www.baidu.com");   
  46.    
  47.          URLConnection con =url.openConnection();   
  48.            
  49.          System.out.println(con);  
  50.      }  
  51.  }  

 

接下来是服务提供类,PhopuRestfulService.java

[源码]
  1.  @Path("/phopuService")  
  2.  public class PhopuRestfulService {  
  3.    
  4.    
  5.      Logger logger = Logger.getLogger(PhopuRestfulServiceImpl.class);  
  6.    
  7.      @GET  
  8.      @Produces(MediaType.APPLICATION_JSON) //指定返回数据的类型 json字符串  
  9.      //@Consumes(MediaType.TEXT_PLAIN) //指定请求数据的类型 文本字符串  
  10.      @Path("/getUser/{userId}")  
  11.      public User getUser(@PathParam("userId")String userId) {  
  12.          this.logger.info("Call getUser() method...."+userId);  
  13.          User user = new User();  
  14.          user.setUserName("中文");  
  15.          user.setAge(26);  
  16.          user.setSex("m");  
  17.          return user;  
  18.      }  
  19.    
  20.      @POST  
  21.      @Produces(MediaType.APPLICATION_JSON) //指定返回数据的类型 json字符串  
  22.      //@Consumes(MediaType.TEXT_PLAIN) //指定请求数据的类型 文本字符串  
  23.      @Path("/getUserPost")  
  24.      public User getUserPost(String userId) {  
  25.          this.logger.info("Call getUserPost() method...."+userId);  
  26.          User user = new User();  
  27.          user.setUserName("中文");  
  28.          user.setAge(26);  
  29.          user.setSex("m");  
  30.          return user;  
  31.      }  
  32.  }  

web.xml配置,跟soap协议的接口一样

[源码]
  1.  <!-- CXF webservice 配置 -->  
  2.      <servlet>  
  3.          <servlet-name>cxf-phopu</servlet-name>  
  4.          <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>  
  5.      </servlet>  
  6.      <servlet-mapping>  
  7.          <servlet-name>cxf-phopu</servlet-name>  
  8.          <url-pattern>/services/*</url-pattern>  
  9.      </servlet-mapping>  

Spring整合配置

 

[源码]
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:p="http://www.springframework.org/schema/p"  
  4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  5.     xmlns:jaxws="http://cxf.apache.org/jaxws"  
  6.     xmlns:jaxrs="http://cxf.apache.org/jaxrs"  
  7.     xsi:schemaLocation="http://www.springframework.org/schema/beans  
  8.         http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
  9.         http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd  
  10.         http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd">  
  11.     <import resource="classpath:/META-INF/cxf/cxf.xml" />  
  12.     <import resource="classpath:/META-INF/cxf/cxf-servlet.xml" />  
  13.     <import resource="classpath:/META-INF/cxf/cxf-extension-soap.xml" />  
  14.   
  15.     <!-- 配置restful json 解析器 , 用CXF自带的JSONProvider需要注意以下几点  
  16.     -1、dropRootElement 默认为false,则Json格式会将类名作为第一个节点,如{Customer:{"id":123,"name":"John"}},如果配置为true,则Json格式为{"id":123,"name":"John"}。  
  17.     -2、dropCollectionWrapperElement属性默认为false,则当遇到Collection时,Json会在集合中将容器中类名作为一个节点,比如{"Customer":{{"id":123,"name":"John"}}},而设置为false,则JSon格式为{{"id":123,"name":"John"}}  
  18.     -3、serializeAsArray属性默认为false,则当遇到Collecion时,格式为{{"id":123,"name":"John"}},如果设置为true,则格式为[{"id":123,"name":"john"}],而Gson等解析为后者  
  19.      
  20.     <bean id="jsonProviders" class="org.apache.cxf.jaxrs.provider.json.JSONProvider">  
  21.         <property name="dropRootElement" value="true" />  
  22.         <property name="dropCollectionWrapperElement" value="true" />  
  23.         <property name="serializeAsArray" value="true" />  
  24.     </bean>  
  25.  -->  
  26.     <!-- 服务类 -->  
  27.     <bean id="phopuService" class="com.phopu.service.PhopuRestfulService" />  
  28.     <jaxrs:server id="service"  address="/">  
  29.         <jaxrs:inInterceptors>  
  30.             <bean class="org.apache.cxf.interceptor.LoggingInInterceptor" />  
  31.         </jaxrs:inInterceptors>  
  32.         <!--serviceBeans:暴露的WebService服务类-->  
  33.         <jaxrs:serviceBeans>  
  34.             <ref bean="phopuService" />  
  35.         </jaxrs:serviceBeans>  
  36.         <!--支持的协议-->  
  37.         <jaxrs:extensionMappings>  
  38.             <entry key="json" value="application/json"/>  
  39.             <entry key="xml" value="application/xml" />  
  40.             <entry key="text" value="text/plain" />  
  41.         </jaxrs:extensionMappings>  
  42.         <!--对象转换-->  
  43.         <jaxrs:providers>  
  44.             <!-- <ref bean="jsonProviders" /> 这个地方直接用CXF的对象转换器会存在问题,当接口发布,第一次访问没问题,但是在访问服务就会报错,等后续在研究下 -->  
  45.             <bean class="org.codehaus.jackson.jaxrs.JacksonJaxbJsonProvider" />  
  46.         </jaxrs:providers>  
  47.     </jaxrs:server>  
  48.       
  49. </beans>  

 

客户端调用示例:

对于get方式的服务,直接在浏览器中输入 http://localhost:8080/phopu/services/phopuService/getUser/101010500 就可以直接看到返回的json字符串 

[源码]
  1. {"userName":"中文","sex":"m","age":26}  

 

客户端调用代码如下:

[源码]
  1.  public static void getWeatherPostTest() throws Exception{  
  2.          String url = "http://localhost:8080/phopu/services/phopuService/getUserPost";  
  3.          HttpClient httpClient = HttpClients.createSystem();  
  4.          //HttpGet httpGet = new HttpGet(url);  //接口get请求,post not allowed  
  5.          HttpPost httpPost = new HttpPost(url);  
  6.          httpPost.addHeader(CONTENT_TYPE_NAME, "text/plain");  
  7.          StringEntity se = new StringEntity("101010500");  
  8.          se.setContentType("text/plain");  
  9.          httpPost.setEntity(se);  
  10.          HttpResponse response = httpClient.execute(httpPost);  
  11.    
  12.          int status = response.getStatusLine().getStatusCode();  
  13.          log.info("[接口返回状态吗] : " + status);  
  14.    
  15.          String weatherInfo = ClientUtil.getReturnStr(response);  
  16.    
  17.          log.info("[接口返回信息] : " + weatherInfo);  
  18.      }  

客户端调用返回信息如下:

ClientUtil类是我自己封装的一个读取response返回信息的类,encoding是UTF-8

 

[源码]
  1.  public static String getReturnStr(HttpResponse response) throws Exception {  
  2.          String result = null;  
  3.          BufferedInputStream buffer = new BufferedInputStream(response.getEntity().getContent());  
  4.          byte[] bytes = new byte[1024];  
  5.          int line = 0;  
  6.          StringBuilder builder = new StringBuilder();  
  7.          while ((line = buffer.read(bytes)) != -1) {  
  8.              builder.append(new String(bytes, 0, line, HTTP_SERVER_ENCODING));  
  9.          }  
  10.          result = builder.toString();  
  11.          return result;  
  12.      }  
原创粉丝点击