在RESTful Web服务时代,我有机会使用SOAP Web Service。 为此,我选择了Spring ,这是因为我们已经在项目中使用Spring作为后端框架,其次它提供了一种直观的方式来与具有明确定义的边界的服务进行交互,以通过WebServiceTemplate促进可重用性和可移植性。

假设您已经了解SOAP Web服务,让我们开始创建在端口9999上运行的hello-world soap服务,并使用下面的步骤来使用相同的客户端:

步骤1 :根据以下图像,转到start.spring.io并创建一个添加Web启动器的新项目soap-server

步骤2:编辑SoapServerApplication.java,以在端点发布hello-world服务-http:// localhost:9999 / service / hello-world ,如下所示:

package com.arpit.soap.server.main;import javax.xml.ws.Endpoint;import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;import com.arpit.soap.server.service.impl.HelloWorldServiceImpl;@SpringBootApplication
public class SoapServerApplication implements CommandLineRunner {@Value("${service.port}")private String servicePort;@Overridepublic void run(String... args) throws Exception {Endpoint.publish("http://localhost:" + servicePort+ "/service/hello-world", new HelloWorldServiceImpl());}public static void main(String[] args) {SpringApplication.run(SoapServerApplication.class, args);}
}

步骤3:编辑application.properties,以指定hello-world服务的应用程序名称,端口和端口号,如下所示:

server.port=9000
spring.application.name=soap-server## Soap Service Port
service.port=9999

步骤4:创建其他包com.arpit.soap.server.servicecom.arpit.soap.server.service.impl来定义Web Service及其实现,如下所示:

HelloWorldService.java

package com.arpit.soap.server.service;import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;import com.arpit.soap.server.model.ApplicationCredentials;@WebService
public interface HelloWorldService {@WebMethod(operationName = "helloWorld", action = "https://aggarwalarpit.wordpress.com/hello-world/helloWorld")String helloWorld(final String name,@WebParam(header = true) final ApplicationCredentials credential);}

上面指定的@WebService将Java类标记为实现Web服务,或者将Java接口标记为定义Web Service接口。

上面指定的@WebMethod将Java方法标记为Web Service操作。

上面指定的@WebParam自定义单个参数到Web服务消息部分和XML元素的映射。

HelloWorldServiceImpl.java

package com.arpit.soap.server.service.impl;import javax.jws.WebService;import com.arpit.soap.server.model.ApplicationCredentials;
import com.arpit.soap.server.service.HelloWorldService;@WebService(endpointInterface = "com.arpit.soap.server.service.HelloWorldService")
public class HelloWorldServiceImpl implements HelloWorldService {@Overridepublic String helloWorld(final String name,final ApplicationCredentials credential) {return "Hello World from " + name;}
}

步骤5:移至soap-server目录并运行命令: mvn spring-boot:run 。 运行后,打开http:// localhost:9999 / service / hello-world?wsdl以查看hello-world服务的WSDL。

接下来,我们将创建soap-client ,它将使用我们新创建的hello-world服务。

步骤6:转到start.spring.io并基于下图创建一个新的项目soap-client,添加Web,Web Services启动程序:

步骤7:编辑SoapClientApplication.java以创建一个向hello-world Web服务的请求,将该请求连同标头一起发送到soap-server并从中获取响应,如下所示:

package com.arpit.soap.client.main;import java.io.IOException;
import java.io.StringWriter;import javax.xml.bind.JAXBElement;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.ws.WebServiceMessage;
import org.springframework.ws.client.core.WebServiceMessageCallback;
import org.springframework.ws.client.core.WebServiceTemplate;
import org.springframework.ws.soap.SoapMessage;
import org.springframework.xml.transform.StringSource;import com.arpit.soap.server.service.ApplicationCredentials;
import com.arpit.soap.server.service.HelloWorld;
import com.arpit.soap.server.service.HelloWorldResponse;
import com.arpit.soap.server.service.ObjectFactory;@SpringBootApplication
@ComponentScan("com.arpit.soap.client.config")
public class SoapClientApplication implements CommandLineRunner {@Autowired@Qualifier("webServiceTemplate")private WebServiceTemplate webServiceTemplate;@Value("#{'${service.soap.action}'}")private String serviceSoapAction;@Value("#{'${service.user.id}'}")private String serviceUserId;@Value("#{'${service.user.password}'}")private String serviceUserPassword;public static void main(String[] args) {SpringApplication.run(SoapClientApplication.class, args);System.exit(0);}public void run(String... args) throws Exception {final HelloWorld helloWorld = createHelloWorldRequest();@SuppressWarnings("unchecked")final JAXBElement<HelloWorldResponse> jaxbElement = (JAXBElement<HelloWorldResponse>) sendAndRecieve(helloWorld);final HelloWorldResponse helloWorldResponse = jaxbElement.getValue();System.out.println(helloWorldResponse.getReturn());}private Object sendAndRecieve(HelloWorld seatMapRequestType) {return webServiceTemplate.marshalSendAndReceive(seatMapRequestType,new WebServiceMessageCallback() {public void doWithMessage(WebServiceMessage message)throws IOException, TransformerException {SoapMessage soapMessage = (SoapMessage) message;soapMessage.setSoapAction(serviceSoapAction);org.springframework.ws.soap.SoapHeader soapheader = soapMessage.getSoapHeader();final StringWriter out = new StringWriter();webServiceTemplate.getMarshaller().marshal(getHeader(serviceUserId, serviceUserPassword),new StreamResult(out));Transformer transformer = TransformerFactory.newInstance().newTransformer();transformer.transform(new StringSource(out.toString()),soapheader.getResult());}});}private Object getHeader(final String userId, final String password) {final https.aggarwalarpit_wordpress.ObjectFactory headerObjectFactory = new https.aggarwalarpit_wordpress.ObjectFactory();final ApplicationCredentials applicationCredentials = new ApplicationCredentials();applicationCredentials.setUserId(userId);applicationCredentials.setPassword(password);final JAXBElement<ApplicationCredentials> header = headerObjectFactory.createApplicationCredentials(applicationCredentials);return header;}private HelloWorld createHelloWorldRequest() {final ObjectFactory objectFactory = new ObjectFactory();final HelloWorld helloWorld = objectFactory.createHelloWorld();helloWorld.setArg0("Arpit");return helloWorld;}}

步骤8:接下来,创建其他包com.arpit.soap.client.config来配置WebServiceTemplate ,如下所示:

ApplicationConfig.java

package com.arpit.soap.client.config;import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.oxm.jaxb.Jaxb2Marshaller;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.ws.client.core.WebServiceTemplate;
import org.springframework.ws.soap.saaj.SaajSoapMessageFactory;
import org.springframework.ws.transport.http.HttpComponentsMessageSender;@Configuration
@EnableWebMvc
public class ApplicationConfig extends WebMvcConfigurerAdapter {@Value("#{'${service.endpoint}'}")private String serviceEndpoint;@Value("#{'${marshaller.packages.to.scan}'}")private String marshallerPackagesToScan;@Value("#{'${unmarshaller.packages.to.scan}'}")private String unmarshallerPackagesToScan;@Beanpublic static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {return new PropertySourcesPlaceholderConfigurer();}@Beanpublic SaajSoapMessageFactory messageFactory() {SaajSoapMessageFactory messageFactory = new SaajSoapMessageFactory();messageFactory.afterPropertiesSet();return messageFactory;}@Beanpublic Jaxb2Marshaller marshaller() {Jaxb2Marshaller marshaller = new Jaxb2Marshaller();marshaller.setPackagesToScan(marshallerPackagesToScan.split(","));return marshaller;}@Beanpublic Jaxb2Marshaller unmarshaller() {Jaxb2Marshaller unmarshaller = new Jaxb2Marshaller();unmarshaller.setPackagesToScan(unmarshallerPackagesToScan.split(","));return unmarshaller;}@Beanpublic WebServiceTemplate webServiceTemplate() {WebServiceTemplate webServiceTemplate = new WebServiceTemplate(messageFactory());webServiceTemplate.setMarshaller(marshaller());webServiceTemplate.setUnmarshaller(unmarshaller());webServiceTemplate.setMessageSender(messageSender());webServiceTemplate.setDefaultUri(serviceEndpoint);return webServiceTemplate;}@Beanpublic HttpComponentsMessageSender messageSender() {HttpComponentsMessageSender httpComponentsMessageSender = new HttpComponentsMessageSender();return httpComponentsMessageSender;}
}

步骤9:编辑application.properties以指定应用程序名称,端口和hello-world soap Web服务配置,如下所示:

server.port=9000
spring.application.name=soap-client## Soap Service Configurationservice.endpoint=http://localhost:9999/service/hello-world
service.soap.action=https://aggarwalarpit.wordpress.com/hello-world/helloWorld
service.user.id=arpit
service.user.password=arpit
marshaller.packages.to.scan=com.arpit.soap.server.service
unmarshaller.packages.to.scan=com.arpit.soap.server.service

上面指定的service.endpoint是提供给服务用户以调用服务提供者公开的服务的URL。

service.soap.action指定服务请求者发送请求时需要调用哪个进程或程序,还定义了进程/程序的相对路径。

marshaller.packages.to.scan指定在将请求发送到服务器之前在编组时要扫描的软件包。

unmarshaller.packages.to.scan指定从服务器收到请求后在解组时要扫描的软件包。

现在,我们将使用wsimport从WSDL生成Java对象,并将其复制到在终端上执行以下命令的soap-client项目:

wsimport -keep -verbose http://localhost:9999/service/hello-world?wsdl

步骤10:移至soap-client目录并运行命令: mvn spring-boot:run 。 命令完成后,我们将在控制台上看到“来自Arpit的Hello World”作为hello-world soap服务的响应。

在运行时,如果遇到以下错误,则– 由于缺少@XmlRootElement批注,因此无法封送键入“ com.arpit.soap.server.service.HelloWorld”作为元素,然后添加@XmlRootElement(name =“ helloWorld”,命名空间= “ http://service.server.soap.arpit.com/ ”到com.arpit.soap.server.service.HelloWorld ,其中名称空间应与在肥皂信封中定义的xmlns:ser相匹配,如下所示:

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ser="http://service.server.soap.arpit.com/"><soapenv:Header><ser:arg1><userId>arpit</userId><password>arpit</password></ser:arg1></soapenv:Header><soapenv:Body><ser:helloWorld><!--Optional:--><arg0>Arpit</arg0></ser:helloWorld></soapenv:Body>
</soapenv:Envelope>

完整的源代码托管在github上 。

翻译自: https://www.javacodegeeks.com/2016/07/writing-consuming-soap-webservice-spring.html

使用Spring编写和使用SOAP Web服务相关推荐

  1. cxf 服务端soap报文_使用Apache CXF开发SOAP Web服务

    cxf 服务端soap报文 在上一篇文章中,我逐步介绍了使用apache CXF开发简单的RESTFull服务的步骤. 在本文中,我将讨论使用CXF开发SOAP Web服务. 在继续前进之前,让我们先 ...

  2. 使用Apache CXF开发SOAP Web服务

    在上一篇文章中,我逐步介绍了使用apache CXF开发简单的RESTFull服务的步骤. 在本文中,我将讨论使用CXF开发SOAP Web服务. 在继续前进之前,让我们了解构成SOAP Web服务的 ...

  3. 使用 Ajax 调用 SOAP Web 服务,第 1 部分: 构建 Web 服务客户机

    James Snell (jasnell@us.ibm.com), 软件工程师,新兴技术, IBM James Snell 是 IBM 的 software group 中的 emerging Int ...

  4. SOAP Web服务

    根据W3C定义,SOAP是什么 " SOAP是一种轻量级协议,旨在在分散的分布式环境中交换结构化信息. 它使用XML技术来定义和扩展消息传递框架,从而提供可以在各种基础协议之间交换的消息构造 ...

  5. mockwebserver java_在Java中使用WireMock和SOAP Web服务

    我是WireMock的创造者. 我最近使用WireMock在客户端项目上模拟了SOAP接口的集合,所以我可以证明它是可能的.至于它是否比SOAP UI更好或更差,我会说有一些明确的好处,但有一些权衡. ...

  6. 如何在ActionScript 3中将“ Null”(真实的姓氏!)传递给SOAP Web服务

    我们有一个姓为Null的员工. 当使用该姓氏作为搜索词时,我们的员工查找应用程序将被杀死(这种情况现在经常发生). 收到的错误(感谢Fiddler!)是: <soapenv:Fault>& ...

  7. Web 服务编程,REST 与 SOAP

    2019独角兽企业重金招聘Python工程师标准>>> 为什么选择 REST 李 三红, 高级软件工程师, IBM 简介: REST 架构风格是一种全新的针对 Web 应用的开发风格 ...

  8. spring创建web项目_使用Spring WS创建合同优先的Web服务

    spring创建web项目 1引言 本文介绍了如何使用来实现和测试SOAP Web服务 Spring Web Services项目 . 本示例将JAXB2用于(取消)编组. 为了开发服务,我将使用合同 ...

  9. c++编写web服务_让我们编写一个文档样式的Web服务

    c++编写web服务 您可能知道,我们可以使用四种主要的Web服务样式. 它们如下: 文件/文学 包装的文件/文学 RPC /编码 RPC /文字 当然,现在不建议使用RPC /编码样式. 如果您有兴 ...

最新文章

  1. 初识Anrdiod SDK
  2. Leet Code OJ 104. Maximum Depth of Binary Tree [Difficulty: Easy]
  3. ASP.NET 之 MVC框架及搭建
  4. BZOJ 2160 拉拉队排练
  5. Retrofit的简单使用
  6. 【Flink】Flink + Drools 构建规则模型
  7. window tomcat 端口冲突问题解决
  8. ORACLE RAC如何增加节点
  9. 前端显示文本时的格式设置
  10. C在mac上用不了malloc.h头文件的解决方法
  11. php语言能开发app吗_如何利用PHP语言开发手机APP
  12. 关于虚拟机,影子系统和游戏机器码的问题
  13. Python中CRAPS游戏,即花旗骰
  14. 浩哥的Linux学习笔记之cp命令
  15. 10 杀手级的网络管理员的工具
  16. 硬盘RAID5后使用的实际容量
  17. ChatGPT讲故事,DALLE-2负责画出来!两大AI合作出绘本!
  18. win7 计算机不显示收藏夹,win7系统下收藏夹无法使用的原因及解决方法
  19. 老毛桃唯一官方网站,现已开发出适应现阶段的U盘启动盘制作工具,让老毛桃传承经典,发扬光大。 http://www.laomaotao.net/?A7510
  20. PHP 常见的数据加密技术

热门文章

  1. 深入Java集合系列之五:PriorityQueue
  2. 浅析负载均衡的6种算法,Ngnix的5种算法
  3. Shell入门(五)之参数
  4. 数据结构(三)之单链表反向查找
  5. Photoshop中将图片拖不进软件的编辑区的解决方法,超详细
  6. 使用加密工具类进行有效的字符串加密——CSDN博客
  7. React中BrowserRouter与HashRouter的区别
  8. 相邻数字+(正月点灯笼的动态规划2)(递归+DP)---JAVA
  9. zookeeper 屁民
  10. 不停机与停机更新_Istio的零停机滚动更新