使用Spring编写和使用SOAP Web服务

在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

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/352662.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

前端---vscode 的基本使用

1. vscode 的基本介绍 全拼是 Visual Studio Code (简称 VS Code) 是由微软研发的一款免费、开源的跨平台代码编辑器&#xff0c;目前是前端(网页)开发使用最多的一款软件开发工具。 2. vscode 的安装 下载网址: Download Visual Studio Code - Mac, Linux, Windows选择对应…

建立Win32 Console Project时会出“error LNK1123” 错误

VS2010在经历一些更新后&#xff0c;建立Win32 Console Project时会出“error LNK1123” 错误&#xff0c;解决方案为将 项目|项目属性|配置属性|清单工具|输入和输出|嵌入清单 “是”改为“否”即可&#xff0c;但是没新建一个项目都要这样设置一次。在建立VS2010 Win32 Proje…

将同时共享的用户数量限制为20_共享充电宝市场需求及计划

18269363827 冯从2016-2018年这些时间中共享充电宝市场空间巨大&#xff0c;据权威数据显示共享充电宝市场整个用户数量实现了从0-5888万的巨大增幅&#xff0c;2019年共享充电市场用户规模将继续保持大幅增长至年底达1亿用户规模。在2019年充电宝租赁市场气势盛大&#xff0c;…

mysql中limit用法

使用查询语句的时候&#xff0c;经常要返回前几条或者中间某几行数据&#xff0c;这个时候怎么办呢&#xff1f;不用担心&#xff0c;mysql已 经为我们提供了这样一个功能。 SELECT*FROMtableLIMIT [offset,]rows |rows OFFSET offsetLIMIT 子句可以被用于强制 SELECT 语句返回…

Redis实现之整数集合

整数集合 整数集合&#xff08;insert&#xff09;是集合键的底层实现之一&#xff0c;当一个集合只包含整数值元素&#xff0c;并且这个集合的元素数量不多时&#xff0c;Redis就会使用整数集合作为集合键的底层实现。举个栗子&#xff0c;如果我们创建一个只包含五个元素的集…

启动rocketmq 报错_RocketMQ为什么要保证订阅关系的一致性?

前段时间有个朋友向我提了一个问题&#xff0c;他说在搭建 RocketMQ 集群过程中遇到了关于消费订阅的问题&#xff0c;具体问题如下&#xff1a;然后他发了报错的日志给我看&#xff1a;the consumers subscription not exist我第一时间在源码里找到了报错的位置&#xff1a;or…

scala rest_使用路标的Scala和Java的Twitter REST API

scala rest如果您已经阅读了此博客上的其他文章&#xff0c;您可能会知道我喜欢创建各种数据集的可视化。 我刚刚开始一个小项目&#xff0c;在这里我想可视化来自Twitter的一些数据。 为此&#xff0c;我想直接从Twitter检索有关关注者的信息和个人资料信息。 我实际上开始寻找…

MySql中关于某列中相同数值连续出现次数的统计

MySql中关于某列中相同数值连续出现次数的统计 原表如下&#xff1a; www.2cto.com 100 101 102 100 100 103 104 102 102 105 106 101 101 输出如下&#xff1a; www.2cto.com 100 1 101 2 102 3 100 4 100 4 103 5 104 6 10…

设计模式之- 外观模式(Facade Pattern)

外观模式 外观模式(Facade Pattern)&#xff1a;外部与一个子系统的通信必须通过一个统一的外观对象进行&#xff0c;为子系统中的一组接口提供一个一致的界面&#xff0c;外观模式定义了一个高层接口&#xff0c;这个接口使得这一子系统更加容易使用。外观模式又称为门面模式&…

python的while和for循环

while语句&#xff0c;提供了编写通用循环的一种方法&#xff0c;而for语句是用来遍历序列对象内的元素&#xff0c;并对每个元素运行一个代码块。break,continue用在循环内&#xff0c;跳出整个循环或者跳出一次循环。 一、while循环 1、一般格式 格式&#xff1a;首行以及测试…

go build 无文件_GO笔记之详解GO的编译执行流程

上篇文章介绍了Golang在不同系统下的安装&#xff0c;并完成了经典的Hello World案例。在这个过程中&#xff0c;我们用到了go run命令&#xff0c;它完成源码从编译到执行的整个过程。今天来详细介绍下这个过程。简单理解&#xff0c;go run 可等价于 go build 执行。 build命…

使用Spring Security和jdbc的Spring Boot第2部分

在上一篇文章中&#xff0c;我们基于Spring Security发出请求的默认表架构实现了安全性。 考虑到用户和角色&#xff0c;应用程序开发人员使用适合其需求的架构。 Spring使我们能够指定所需的查询&#xff0c;以便检索用户名&#xff0c;密码和角色等信息。 我们的自定义表将…

MySQL的一些简单语句

mysql 统计 表的数量&#xff1a;SELECT COUNT(1) FROM information_schema.TABLES WHERE TABLE_SCHEMA 你的数据库; MySQL的一些基础语句&#xff1a; 行是记录 列是字段 创建库 CREATE DATABASE [IF NOT EXISTS] 数据库名 [参数[ 参数] [ 参数]...]; 参数: CHARACTER …

【题解】Atcoder ARC#90 F-Number of Digits

Atcoder刷不动的每日一题... 首先注意到一个事实&#xff1a;随着 \(l, r\) 的增大&#xff0c;\(f(r) - f(l)\) 会越来越小。考虑暴力处理出小数据的情况&#xff0c;我们可以发现对于左端点 \(f(l) < 7\) 的情况下&#xff0c;右端点的最大限度为 \(\frac{10^8}{8} 10^7…

java分页查询_面试官:数据量很大,分页查询很慢,有什么优化方案?

准备工作一般分页查询使用子查询优化使用 id 限定优化使用临时表优化关于数据表的id说明《Java 2019 超神之路》《Dubbo 实现原理与源码解析 —— 精品合集》《Spring 实现原理与源码解析 —— 精品合集》《MyBatis 实现原理与源码解析 —— 精品合集》《Spring MVC 实现原理与…

Python逐行读取文件内容

f open("foo.txt") # 返回一个文件对象 line f.readline() # 调用文件的 readline()方法 while line:print line, # 后面跟 , 将忽略换行符# print(line, end )   # 在 Python 3中使用line f.readline()f.close() 也…

原型模式精讲

原型模式是一种创建型模式,也是属于创建对象的一种方式,像西游记里面的孙悟空吹猴毛也属于原型模式,克隆出来了一群的猴子猴孙,还有细胞的分裂,spring中的Bean的生命周期好像有一个单例还有个原型&#xff0c;那个原型就是每次请求都复制一个对象出来,官方的定义是:用原型实例指…

Python中map()函数浅析

MapReduce的设计灵感来自于函数式编程&#xff0c;这里不打算提MapReduce&#xff0c;就拿python中的map()函数来学习一下。 文档中的介绍在这里&#xff1a; map(function, iterable, ...) Apply function to every item of iterable and return a list of the results. If ad…

选择与循环:剪刀石头布_Python之石头剪刀布小游戏(史上最详细步骤)

​嗨&#xff0c;各位好呀&#xff0c;我是真小凡。相信你如果是一个刚学习Python的小白&#xff0c;一定会很想做一个自己的Python小游戏&#xff08;我就是这样子的&#xff09;&#xff0c;那么今天我们就一起实操一下&#xff01;首先要清楚&#xff0c;做一个项目必须的流…

cometd_CometD:Java Web应用程序的Facebook类似聊天

cometd聊天就像吃一块蛋糕或喝一杯热咖啡一样容易。 您是否曾经考虑过自己开发聊天程序&#xff1f; 您知道&#xff0c;聊天不容易。 但是&#xff0c;如果您是开发人员&#xff0c;并且阅读了本文的最后部分&#xff0c;则可以尝试自行开发一个聊天应用程序&#xff0c;并允许…