Spring整合CXF webservice restful实例详解

发布时间 - 2026-01-11 02:43:48    点击率:

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);
  }

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

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;
  }

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

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


# Spring  # CXF  # webservice  # restful  # 详解Spring boot+CXF开发WebService Demo  # Spring boot 整合CXF开发web service示例  # spring整合cxf框架实例  # Spring Boot 实现Restful webservice服务端示例代码  # spring如何集成cxf实现webservice接口功能详解  # 格式为  # 默认为  # 客户端  # 设置为  # 就可以  # 就会  # 第一个  # 会在  # 作为一个  # 几点  # 大同小异  # 自带  # 报错  # 会将  # 需要注意  # 大家多多  # 存在问题  # 器中  # 但是在  # 只是在 


相关栏目: 【 网站优化151355 】 【 网络推广146373 】 【 网络技术251813 】 【 AI营销90571


相关推荐: Laravel如何使用Sanctum进行API认证?(SPA实战)  如何快速搭建高效香港服务器网站?  大型企业网站制作流程,做网站需要注册公司吗?  Laravel的契約(Contracts)是什么_深入理解Laravel Contracts与依赖倒置  Laravel怎么创建自己的包(Package)_Laravel扩展包开发入门到发布  如何撰写建站申请书?关键要点有哪些?  Laravel Eloquent访问器与修改器是什么_Laravel Accessors & Mutators数据处理技巧  网站设计制作书签怎么做,怎样将网页添加到书签/主页书签/桌面?  Laravel如何为API编写文档_Laravel API文档生成与维护方法  Win10如何卸载预装Edge扩展_Win10卸载Edge扩展教程【方法】  韩国服务器如何优化跨境访问实现高效连接?  如何在阿里云虚拟主机上快速搭建个人网站?  如何在七牛云存储上搭建网站并设置自定义域名?  Laravel怎么配置S3云存储驱动_Laravel集成阿里云OSS或AWS S3存储桶【教程】  HTML5空格和margin有啥区别_空格与外边距的使用场景【说明】  Laravel如何配置Horizon来管理队列?(安装和使用)  Laravel控制器是什么_Laravel MVC架构中Controller的作用与实践  Laravel怎么清理缓存_Laravel optimize clear命令详解  如何在IIS中配置站点IP、端口及主机头?  Laravel如何监控和管理失败的队列任务_Laravel失败任务处理与监控  JavaScript如何实现类型判断_typeof和instanceof有什么区别  成都品牌网站制作公司,成都营业执照年报网上怎么办理?  如何在局域网内绑定自建网站域名?  Laravel怎么多语言本地化设置_Laravel语言包翻译与Locale动态切换【手册】  C#如何调用原生C++ COM对象详解  Laravel如何实现模型的全局作用域?(Global Scope示例)  JavaScript Ajax实现异步通信  如何破解联通资金短缺导致的基站建设难题?  邀请函制作网站有哪些,有没有做年会邀请函的网站啊?在线制作,模板很多的那种?  Laravel如何保护应用免受CSRF攻击?(原理和示例)  VIVO手机上del键无效OnKeyListener不响应的原因及解决方法  Laravel用户认证怎么做_Laravel Breeze脚手架快速实现登录注册功能  如何用IIS7快速搭建并优化网站站点?  Laravel软删除怎么实现_Laravel Eloquent SoftDeletes功能使用教程  Laravel如何实现RSS订阅源功能_Laravel动态生成网站XML格式订阅内容【教程】  Laravel如何清理系统缓存命令_Laravel清除路由配置及视图缓存的方法【总结】  Laravel如何实现URL美化Slug功能_Laravel使用eloquent-sluggable生成别名【方法】  如何做网站制作流程,*游戏网站怎么搭建?  Laravel distinct去重查询_Laravel Eloquent去重方法  如何在 Pandas 中基于一列条件计算另一列的分组均值  Laravel怎么实现API接口鉴权_Laravel Sanctum令牌生成与请求验证【教程】  Laravel怎么判断请求类型_Laravel Request isMethod用法  Android中Textview和图片同行显示(文字超出用省略号,图片自动靠右边)  怎么用AI帮你设计一套个性化的手机App图标?  jQuery中的100个技巧汇总  如何为不同团队 ID 动态生成多个非值班状态按钮  Javascript中的事件循环是如何工作的_如何利用Javascript事件循环优化异步代码?  如何在景安云服务器上绑定域名并配置虚拟主机?  Laravel怎么使用Intervention Image库处理图片上传和缩放  如何在腾讯云免费申请建站?