欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Spring整合CXF webservice restful实例详解

程序员文章站 2024-03-31 10:40:46
webservice restful接口跟soap协议的接口实现大同小异,只是在提供服务的类/接口的注解上存在差异,具体看下面的代码,然后自己对比下就可以了。 用到的基础...

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

用到的基础类

user.java

@xmlrootelement(name="user")
public class user {

  private string username;
  private string sex;
  private int age;
  
  public user(string username, string sex, int age) {
    super();
    this.username = username;
    this.sex = sex;
    this.age = age;
  }
  
  public user() {
    super();
  }

  public string getusername() {
    return username;
  }
  public void setusername(string username) {
    this.username = username;
  }
  public string getsex() {
    return sex;
  }
  public void setsex(string sex) {
    this.sex = sex;
  }
  public int getage() {
    return age;
  }
  public void setage(int age) {
    this.age = age;
  }
  
  public static void main(string[] args) throws ioexception {
    system.setproperty("http.proxyset", "true"); 

    system.setproperty("http.proxyhost", "192.168.1.20"); 

    system.setproperty("http.proxyport", "8080");
    
    url url = new url("http://www.baidu.com"); 

    urlconnection con =url.openconnection(); 
    
    system.out.println(con);
  }
}

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

@path("/phopuservice")
public class phopurestfulservice {


  logger logger = logger.getlogger(phopurestfulserviceimpl.class);

  @get
  @produces(mediatype.application_json) //指定返回数据的类型 json字符串
  //@consumes(mediatype.text_plain) //指定请求数据的类型 文本字符串
  @path("/getuser/{userid}")
  public user getuser(@pathparam("userid")string userid) {
    this.logger.info("call getuser() method...."+userid);
    user user = new user();
    user.setusername("中文");
    user.setage(26);
    user.setsex("m");
    return user;
  }

  @post
  @produces(mediatype.application_json) //指定返回数据的类型 json字符串
  //@consumes(mediatype.text_plain) //指定请求数据的类型 文本字符串
  @path("/getuserpost")
  public user getuserpost(string userid) {
    this.logger.info("call getuserpost() method...."+userid);
    user user = new user();
    user.setusername("中文");
    user.setage(26);
    user.setsex("m");
    return user;
  }
}

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

<!-- cxf webservice 配置 -->
  <servlet>
    <servlet-name>cxf-phopu</servlet-name>
    <servlet-class>org.apache.cxf.transport.servlet.cxfservlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>cxf-phopu</servlet-name>
    <url-pattern>/services/*</url-pattern>
  </servlet-mapping>

spring整合配置

<?xml version="1.0" encoding="utf-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:p="http://www.springframework.org/schema/p"
  xmlns:xsi="http://www.w3.org/2001/xmlschema-instance"
  xmlns:jaxws="http://cxf.apache.org/jaxws"
  xmlns:jaxrs="http://cxf.apache.org/jaxrs"
  xsi:schemalocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd
    http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd">
  <import resource="classpath:/meta-inf/cxf/cxf.xml" />
  <import resource="classpath:/meta-inf/cxf/cxf-servlet.xml" />
  <import resource="classpath:/meta-inf/cxf/cxf-extension-soap.xml" />

  <!-- 配置restful json 解析器 , 用cxf自带的jsonprovider需要注意以下几点
  -1、droprootelement 默认为false,则json格式会将类名作为第一个节点,如{customer:{"id":123,"name":"john"}},如果配置为true,则json格式为{"id":123,"name":"john"}。
  -2、dropcollectionwrapperelement属性默认为false,则当遇到collection时,json会在集合中将容器中类名作为一个节点,比如{"customer":{{"id":123,"name":"john"}}},而设置为false,则json格式为{{"id":123,"name":"john"}}
  -3、serializeasarray属性默认为false,则当遇到collecion时,格式为{{"id":123,"name":"john"}},如果设置为true,则格式为[{"id":123,"name":"john"}],而gson等解析为后者
  
  <bean id="jsonproviders" class="org.apache.cxf.jaxrs.provider.json.jsonprovider">
    <property name="droprootelement" value="true" />
    <property name="dropcollectionwrapperelement" value="true" />
    <property name="serializeasarray" value="true" />
  </bean>
 -->
  <!-- 服务类 -->
  <bean id="phopuservice" class="com.phopu.service.phopurestfulservice" />
  <jaxrs:server id="service" address="/">
    <jaxrs:ininterceptors>
      <bean class="org.apache.cxf.interceptor.loggingininterceptor" />
    </jaxrs:ininterceptors>
    <!--servicebeans:暴露的webservice服务类-->
    <jaxrs:servicebeans>
      <ref bean="phopuservice" />
    </jaxrs:servicebeans>
    <!--支持的协议-->
    <jaxrs:extensionmappings>
      <entry key="json" value="application/json"/>
      <entry key="xml" value="application/xml" />
      <entry key="text" value="text/plain" />
    </jaxrs:extensionmappings>
    <!--对象转换-->
    <jaxrs:providers>
      <!-- <ref bean="jsonproviders" /> 这个地方直接用cxf的对象转换器会存在问题,当接口发布,第一次访问没问题,但是在访问服务就会报错,等后续在研究下 -->
      <bean class="org.codehaus.jackson.jaxrs.jacksonjaxbjsonprovider" />
    </jaxrs:providers>
  </jaxrs:server>
  
</beans>

客户端调用示例:

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

{"username":"中文","sex":"m","age":26} 

客户端调用代码如下:

public static void getweatherposttest() throws exception{
    string url = "http://localhost:8080/phopu/services/phopuservice/getuserpost";
    httpclient httpclient = httpclients.createsystem();
    //httpget httpget = new httpget(url); //接口get请求,post not allowed
    httppost httppost = new httppost(url);
    httppost.addheader(content_type_name, "text/plain");
    stringentity se = new stringentity("101010500");
    se.setcontenttype("text/plain");
    httppost.setentity(se);
    httpresponse response = httpclient.execute(httppost);

    int status = response.getstatusline().getstatuscode();
    log.info("[接口返回状态吗] : " + status);

    string weatherinfo = clientutil.getreturnstr(response);

    log.info("[接口返回信息] : " + weatherinfo);
  }

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

Spring整合CXF webservice restful实例详解

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

public static string getreturnstr(httpresponse response) throws exception {
    string result = null;
    bufferedinputstream buffer = new bufferedinputstream(response.getentity().getcontent());
    byte[] bytes = new byte[1024];
    int line = 0;
    stringbuilder builder = new stringbuilder();
    while ((line = buffer.read(bytes)) != -1) {
      builder.append(new string(bytes, 0, line, http_server_encoding));
    }
    result = builder.tostring();
    return result;
  }

到这里,就介绍完了,大家手动去操作一下吧,有问题大家一块交流。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。