前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >springMvc项目集成cxf实现webService通信方式的详细步骤

springMvc项目集成cxf实现webService通信方式的详细步骤

作者头像
跟着飞哥学编程
发布2022-11-30 21:26:21
1.1K0
发布2022-11-30 21:26:21
举报

目录

Web Service基本概念

调用原理

环境配置

 pom.xml引入jar包依赖

web.xml设置servelet

 添加webService服务接口的bean文件 applicationContext-cxf.xml

提供webservice服务端接口(此处如果项目不需要对外提供服务可以跳过)

 编写webService服务的java类

 客户端调用webService服务

基于动态代理工厂类JaxWsDynamicClientFactory调用

基于httpclient调用webservice服务


Web Service基本概念

Web Service也叫XML Web Service WebService是一种可以接收从Internet或者Intranet上的其它系统中传递过来的请求,轻量级的独立的通讯技术。是:通过SOAP在Web上提供的软件服务,使用WSDL文件进行说明,并通过UDDI进行注册。

XML:(Extensible Markup Language)扩展型可标记语言。面向短期的临时数据处理、面向万维网络,是Soap的基础。

Soap:(Simple Object Access Protocol)简单对象存取协议。是XML Web Service 的通信协议。当用户通过UDDI找到你的WSDL描述文档后,他通过可以SOAP调用你建立的Web服务中的一个或多个操作。SOAP是XML文档形式的调用方法的规范,它可以支持不同的底层接口,像HTTP(S)或者SMTP。

WSDL:(Web Services Description Language) WSDL 文件是一个 XML 文档,用于说明一组 SOAP 消息以及如何交换这些消息。大多数情况下由软件自动生成和使用。

UDDI (Universal Description, Discovery, and Integration) 是一个主要针对Web服务供应商和使用者的新项目。在用户能够调用Web服务之前,必须确定这个服务内包含哪些方法,找到被调用的接口定义,还要在服务端来编制软件,UDDI是一种根据描述文档来引导系统查找相应服务的机制。UDDI利用SOAP消息机制(标准的XML/HTTP)来发布,编辑,浏览以及查找注册信息。它采用XML格式来封装各种不同类型的数据,并且发送到注册中心或者由注册中心来返回需要的数据。

调用原理

环境配置

 pom.xml引入jar包依赖

代码语言:javascript
复制
<dependency>
    <groupId>org.apache.cxf</groupId>
    <artifactId>cxf-core</artifactId>
    <version>3.1.11</version>
</dependency>
<dependency>
    <groupId>org.apache.cxf</groupId>
    <artifactId>cxf-rt-frontend-jaxws</artifactId>
    <version>3.1.11</version>
</dependency>
<dependency>
    <groupId>org.apache.cxf</groupId>
    <artifactId>cxf-rt-transports-http</artifactId>
    <version>3.1.11</version>
</dependency>
<!-- 加入cxf-restful依赖包 -->
<dependency>
    <groupId>org.apache.cxf</groupId>
    <artifactId>cxf-rt-frontend-jaxrs</artifactId>
    <version>3.1.11</version>
</dependency> 

web.xml设置servelet

代码语言:javascript
复制
<servlet>
    <servlet-name>CXFService</servlet-name>
    <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>CXFService</servlet-name>
    <url-pattern>/webService/*</url-pattern>
</servlet-mapping>

 注意:添加位置别搞错啦如下图:

 添加webService服务接口的bean文件 applicationContext-cxf.xml

注意文件位置:此处我web.xml配置的xml扫描路劲为 

 因此我的文件是在src/main/resources/spring/applicationContext-cxf.xml,文件内容如下

代码语言:javascript
复制
<?xml version="1.1" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:jaxws="http://cxf.apache.org/jaxws"
    xmlns:soap="http://cxf.apache.org/bindings/soap"
    xsi:schemaLocation="
       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
       http://cxf.apache.org/bindings/soap http://cxf.apache.org/schemas/configuration/soap.xsd
       http://cxf.apache.org/jaxws
       http://cxf.apache.org/schemas/jaxws.xsd ">
    
    <import resource="classpath:META-INF/cxf/cxf.xml" />
    <import resource="classpath:META-INF/cxf/cxf-servlet.xml" />
	
	<bean id="CommonWebServiceServerService" class="com.xxx.common.webService.impl.CommonWebServiceServerServiceImpl" />
	<jaxws:endpoint implementor = "#CommonWebServiceServerService" address="/webServiceServer" publish="true" />
 	
</beans>

提供webservice服务端接口(此处如果项目不需要对外提供服务可以跳过)

 编写webService服务的java类

先写一个interface接口

代码语言:javascript
复制
package com.xxx.common.webService;

public interface CommonWebServiceServerService {
	
    String commonMethod( String xmlData);
    
}

再写它的实现类:

代码语言:javascript
复制
package com.xxx.common.webService.impl;

import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@WebService(targetNamespace = "http://webService.common.xxx.com")
public class CommonWebServiceServerServiceImpl implements CommonWebServiceServerService{

	private static final Logger logger = LoggerFactory.getLogger(CommonWebServiceServerServiceImpl.class);
@WebMethod
	@WebResult(targetNamespace = "http://webService.common.xxx.com")
    public String commonMethod(@WebParam(targetNamespace = "http://webService.common.xxx.com") String xmlData){
		long start = System.currentTimeMillis();
		logger.info("接收第三方(webservice)报文:{}", xmlData);
		String retXml = "";
		try {
			//此处写你具体的业务逻辑处理并返回客户端响应
		} catch (Exception e) {
			logger.error("接收第三方(webservice)报文处理异常:{}", e);
			
		}  finally {
			logger.info("处理第三方(webservice)请求花费的时间为:{}毫秒", System.currentTimeMillis()-start);
		}
		return retXml;
	}
}

 注意:命名空间targetNamespace 是你接口所在的package包名倒装的全路径

 客户端调用webService服务

客户端调用的方式有多种,个人认为根据自己实际情况使用吧

基于动态代理工厂类JaxWsDynamicClientFactory调用

目录

环境配置

 pom.xml引入jar包依赖

web.xml设置servelet

 添加webService服务接口的bean文件 applicationContext-cxf.xml

提供webservice服务端接口(此处如果项目不需要对外提供服务可以跳过)

 编写webService服务的java类

 客户端调用webService服务

基于动态代理工厂类JaxWsDynamicClientFactory调用

基于httpclient调用webservice服务


基于httpclient调用webservice服务

代码语言:javascript
复制
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.InputStreamRequestEntity;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;

public class HttpClientTest {
static String wsdl = "http://ip:port/webService/webServiceServer?wsdl";
static String ns = "http://webService.common.xxx.com";//命名空间
static String method = "commonMethod";//方法名
	/**
     * 访问服务
     *
     * @param wsdl   wsdl地址
     * @param ns     命名空间
     * @param method 方法名
     * @param req_xml 请求参数
     * @return
     * @throws Exception
     */
    public synchronized static String accessService(String wsdl, String ns, String method,String reqXml) throws Exception {

        String soapResponseData = "";
    	StringBuffer soapRequestData = new StringBuffer("");
        soapRequestData.append("<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ser=\""+ns+"\">");
        soapRequestData.append("<soapenv:Header/>");
        soapRequestData.append("<soapenv:Body>");
        soapRequestData.append("<ser:" + method + ">");
        soapRequestData.append("<arg0>"+reqXml+"</arg0>");
        soapRequestData.append("</ser:" + method + ">");
        soapRequestData.append("</soapenv:Body>" + "</soapenv:Envelope>");
        PostMethod postMethod = new PostMethod(wsdl);
        // 然后把Soap请求数据添加到PostMethod中
        byte[] b = null;
        InputStream is = null;
        try {
            b = soapRequestData.toString().getBytes("utf-8");
            is = new ByteArrayInputStream(b, 0, b.length);
            RequestEntity re = new InputStreamRequestEntity(is, b.length, "application/soap+xml; charset=UTF-8");
            postMethod.setRequestEntity(re);
            HttpClient httpClient = new HttpClient();
            int status = httpClient.executeMethod(postMethod);
            if (status == 200) {
            	System.out.println("成功调用webService接口返回内容:"+postMethod.getResponseBodyAsString());
                soapResponseData = getMesage(postMethod.getResponseBodyAsString());
            }else {
            	System.out.println("调用webService接口失败:STATUS:"+status);
            	System.out.println("httpPost方式调用webservice服务异常:"+postMethod.getResponseBodyAsString());
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                is.close();
            }
        }
        return soapResponseData;
    }

    public static String getMesage(String soapAttachment) {
        if (soapAttachment != null && soapAttachment.length() > 0) {
            int begin = soapAttachment.indexOf("<return>");
            begin = soapAttachment.indexOf(">", begin);
            int end = soapAttachment.indexOf("</return>");
            String str = soapAttachment.substring(begin + 1, end);
            str=str.replace("&lt;", "<");
            str=str.replace("&quot;", "\"");
            str=str.replace("&gt;", ">");
            return str;
        } else {
            return "";
        }
    }

}

上面为工具类,如有不合适可以根据自己的请求内容作出修改,调用方式

String response = accessService(wsdl, ns, method,reqXml);

还有一种axis2调用webService的方式 

感兴趣的可以自己下去研究,小编是在曾经一次项目中调用银行的接口时用过一次,就是多种方式,如果上述两种方式都有问题时,再考虑第三种。因为cxf需要服务端和客户端的版本一致。所以有时候包的版本不一致时,会有问题。 

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2022-03-16,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Web Service基本概念
  • 调用原理
  • 环境配置
    •  pom.xml引入jar包依赖
      • web.xml设置servelet
        •  添加webService服务接口的bean文件 applicationContext-cxf.xml
        • 提供webservice服务端接口(此处如果项目不需要对外提供服务可以跳过)
          •  编写webService服务的java类
          •  客户端调用webService服务
            • 基于动态代理工厂类JaxWsDynamicClientFactory调用
              • 基于httpclient调用webservice服务
              相关产品与服务
              微服务引擎 TSE
              微服务引擎(Tencent Cloud Service Engine)提供开箱即用的云上全场景微服务解决方案。支持开源增强的云原生注册配置中心(Zookeeper、Nacos 和 Apollo),北极星网格(腾讯自研并开源的 PolarisMesh)、云原生 API 网关(Kong)以及微服务应用托管的弹性微服务平台。微服务引擎完全兼容开源版本的使用方式,在功能、可用性和可运维性等多个方面进行增强。
              领券
              问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档