javascript
使用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.service和com.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服务的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java生产力提示:社区的热门选择
- 下一篇: 使用Spring Security和jd