iis服务器助手广告广告
返回顶部
首页 > 资讯 > 精选 >如何在Spring中利用webservice restful对CXF 进行整合
  • 240
分享到

如何在Spring中利用webservice restful对CXF 进行整合

springcxfwebservice 2023-05-31 07:05:28 240人浏览 泡泡鱼
摘要

今天就跟大家聊聊有关如何在spring中利用WEBservice restful对CXF 进行整合,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。webservice restful接

今天就跟大家聊聊有关如何在spring中利用WEBservice restful对CXF 进行整合,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

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中利用webservice restful对CXF 进行整合

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中利用webservice restful对CXF 进行整合有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注编程网精选频道,感谢大家的支持。

--结束END--

本文标题: 如何在Spring中利用webservice restful对CXF 进行整合

本文链接: https://www.lsjlt.com/news/224282.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作