用Springboot搭建webService服务

概述

WebService简单概述就是用http发送接收xml数据,但这个xml得遵守系统的规范。这个规范就是WSDL(Web服务描述语言,Web Services Description Language),在WebService中传输的xml有一个正式的名称叫Soap(简单对象访问协议 Simple Object Access Protocol)。

代码实现

  1. 首先,准备一个wsdl 文档
    wsdl 文档包含五个标准元素:types, message, portType, binding and service。
    wsdl 提供 3 种操作:deleteTutorial、updateTutorial 和 getTutorials。
<?xml version="1.0" encoding="UTF-8"?>
<definitions name="someName"
	targetNamespace="http://www.wstutorial.com/ws/TutorialService" xmlns="http://schemas.xmlsoap.org/wsdl/"
	xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:xs="http://www.w3.org/2001/XMLSchema"
	xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:tns="http://www.wstutorial.com/ws/TutorialService">

	<types>
		<xs:schema targetNamespace="http://www.wstutorial.com/ws/TutorialService">
			<xs:complexType name="statusCode">
				<xs:sequence>
					<xs:element name="code" type="xs:long" />
				</xs:sequence>
			</xs:complexType>
			<xs:complexType name="TutorialType">
				<xs:all>
					<xs:element name="id" type="xs:long" />
					<xs:element name="name" type="xs:string" />
					<xs:element name="author" type="xs:string" />
				</xs:all>
			</xs:complexType>

			<xs:element name="updateTutorialRequest">
				<xs:complexType>
					<xs:sequence>
						<xs:element name="tutorialType" type="tns:TutorialType" />
					</xs:sequence>
				</xs:complexType>
			</xs:element>

			<xs:element name="updateTutorialResponse">
				<xs:complexType>
					<xs:sequence>
						<xs:element name="statusCode" type="tns:statusCode" />
					</xs:sequence>
				</xs:complexType>
			</xs:element>

			<xs:element name="deleteTutorialRequest">
				<xs:complexType>
					<xs:sequence>
						<xs:element name="id" type="xs:long" />
					</xs:sequence>
				</xs:complexType>
			</xs:element>

			<xs:element name="deleteTutorialResponse">
				<xs:complexType>
					<xs:sequence>
						<xs:element name="statusCode" type="tns:statusCode" />
					</xs:sequence>
				</xs:complexType>
			</xs:element>

			<xs:element name="getTutorialsRequest">
				<xs:complexType>
					<xs:sequence>
						<xs:element name="id" type="xs:long" />
					</xs:sequence>
				</xs:complexType>
			</xs:element>

			<xs:element name="getTutorialsResponse">
				<xs:complexType>
					<xs:sequence>
						<xs:element type="tns:TutorialType" minOccurs="0"
							maxOccurs="unbounded" name="tutorials" />
					</xs:sequence>
				</xs:complexType>
			</xs:element>

			<xs:complexType name="TutorialTypes">
				<xs:sequence>
					<xs:element type="tns:TutorialType" minOccurs="0"
						maxOccurs="unbounded" name="tutorials" />
				</xs:sequence>
			</xs:complexType>

			<xs:element name="tutorialFault" type="xs:string" />
		</xs:schema>
	</types>

	<message name="tutorialFault">
		<part name="params" element="tns:tutorialFault" />
	</message>

	<message name="getTutorialsRequestMsg">
		<part name="params" element="tns:getTutorialsRequest" />
	</message>
	<message name="getTutorialsResponseMsg">
		<part name="params" element="tns:getTutorialsResponse" />
	</message>

	<message name="deleteTutorialRequestMsg">
		<part name="params" element="tns:deleteTutorialRequest" />
	</message>
	<message name="deleteTutorialResponseMsg">
		<part name="params" element="tns:deleteTutorialResponse" />
	</message>

	<message name="updateTutorialRequestMsg">
		<part name="params" element="tns:updateTutorialRequest" />
	</message>
	<message name="updateTutorialResponseMsg">
		<part name="params" element="tns:updateTutorialResponse" />
	</message>

	<portType name="TutorialServicePortType">
		<operation name="deleteTutorial">
			<input message="tns:deleteTutorialRequestMsg" />
			<output message="tns:deleteTutorialResponseMsg" />
			<fault name="fault" message="tns:tutorialFault" />
		</operation>
		<operation name="updateTutorial">
			<input message="tns:updateTutorialRequestMsg" />
			<output message="tns:updateTutorialResponseMsg" />
			<fault name="fault" message="tns:tutorialFault" />
		</operation>
		<operation name="getTutorials">
			<input message="tns:getTutorialsRequestMsg" />
			<output message="tns:getTutorialsResponseMsg" />
			<fault name="fault" message="tns:tutorialFault" />
		</operation>
	</portType>

	<binding name="tutorialServiceSOAPBinding" type="tns:TutorialServicePortType">
		<soap:binding style="document"
			transport="http://schemas.xmlsoap.org/soap/http" />
		<operation name="deleteTutorial">
			<soap:operation soapAction="deleteTutorial" />
			<input>
				<soap:body use="literal" />
			</input>
			<output>
				<soap:body use="literal" />
			</output>
			<fault name="fault">
				<soap:fault name="fault" use="literal" />
			</fault>
		</operation>
		<operation name="updateTutorial">
			<soap:operation soapAction="updateTutorial" />
			<input>
				<soap:body use="literal" />
			</input>
			<output>
				<soap:body use="literal" />
			</output>
			<fault name="fault">
				<soap:fault name="fault" use="literal" />
			</fault>
		</operation>
		<operation name="getTutorials">
			<soap:operation soapAction="getTutorials" />
			<input>
				<soap:body use="literal" />
			</input>
			<output>
				<soap:body use="literal" />
			</output>
			<fault name="fault">
				<soap:fault name="fault" use="literal" />
			</fault>
		</operation>
	</binding>
	<service name="TutorialService">
		<port name="TutorialServicePort" binding="tns:tutorialServiceSOAPBinding">
			<soap:address
				location="http://localhost:8080/wsdlfirst/tutorialService" />
		</port>
	</service>
</definitions>
  1. 创建SpringBoot项目,Pom文件添加WebService依赖
    在这里插入图片描述
    唯一使用的依赖项是 spring-boot-starter-web-services,它包括 Spring-WS依赖项
    Maven 插件 maven-jaxb2-plugin 从 WSDL文件生成 Java 源代码
  • schemaDirectory:可以找到 WSDL 文件存放的目录。
  • schemaIncludes:在这里我们可以指定应该使用哪个文件。
  • generatePackage:生成代码的包名
  • generateDirectory :生成代码的目标目录
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web-services</artifactId>
</dependency>

<plugin>
    <groupId>org.jvnet.jaxb2.maven2</groupId>
    <artifactId>maven-jaxb2-plugin</artifactId>
    <version>0.13.2</version>
    <executions>
        <execution>
            <goals>
                <goal>generate</goal>
            </goals>
        </execution>
    </executions>
    <configuration>
        <schemaLanguage>WSDL</schemaLanguage>
        <generatePackage>com.ping.wsdl.tutorialService</generatePackage>
        <generateDirectory>src/main/java</generateDirectory>
        <schemaDirectory>${project.basedir}/src/main/resources/wsdl</schemaDirectory>
        <schemaIncludes>
            <include>*.wsdl</include>
        </schemaIncludes>
    </configuration>
</plugin>
        

双击generate生成源代码
在这里插入图片描述
在这里插入图片描述

  1. 实现Endpoint
package com.ping.wsdl.service;

import java.util.ArrayList;
import java.util.List;

import com.ping.wsdl.tutorialService.*;
import org.springframework.ws.server.endpoint.annotation.Endpoint;
import org.springframework.ws.server.endpoint.annotation.PayloadRoot;
import org.springframework.ws.server.endpoint.annotation.RequestPayload;
import org.springframework.ws.server.endpoint.annotation.ResponsePayload;



@Endpoint
public class TutorialServiceEndpoint {
    
    
    private static final String NAMESPACE_URI = "http://www.wstutorial.com/ws/TutorialService";


    @PayloadRoot(namespace = NAMESPACE_URI, localPart = "updateTutorialRequest" )
    @ResponsePayload
    public UpdateTutorialResponse updateTutorial(@RequestPayload UpdateTutorialRequest request)throws Exception  {
    
    
        ObjectFactory factory = new ObjectFactory();
        StatusCode code = factory.createStatusCode();
        UpdateTutorialResponse response = factory.createUpdateTutorialResponse();
        code.setCode(200);
        response.setStatusCode(code);
        return response;
    }

    @PayloadRoot(namespace = NAMESPACE_URI, localPart = "deleteTutorialRequest" )
    @ResponsePayload
    public DeleteTutorialResponse deleteTutorial(@RequestPayload DeleteTutorialRequest request)throws Exception  {
    
    
        System.out.println("-->deleteTutorial<--");
        ObjectFactory factory = new ObjectFactory();
        DeleteTutorialResponse response = factory.createDeleteTutorialResponse();
        StatusCode code = factory.createStatusCode();
        code.setCode(204);
        response.setStatusCode(code);
        return response;
    }

    @PayloadRoot(namespace = NAMESPACE_URI, localPart = "getTutorialsRequest" )
    @ResponsePayload
    public GetTutorialsResponse getTutorials(@RequestPayload GetTutorialsRequest request)throws Exception  {
    
    
        ObjectFactory factory = new ObjectFactory();
        GetTutorialsResponse response = factory.createGetTutorialsResponse();

        List<TutorialType> tutorials = getTutorials();

        response.getTutorials().addAll(tutorials);
        return response;
    }

    private List<TutorialType> getTutorials() {
    
    
        List<TutorialType> tutorials= new ArrayList<TutorialType>();
        TutorialType tut1 = new TutorialType();
        tut1.setAuthor("John Doe");
        tut1.setId(15l);
        tut1.setName("Web Service with spring boot");

        TutorialType tut2 = new TutorialType();
        tut2.setAuthor("John Doe");
        tut2.setId(152);
        tut2.setName("Web Service with spring boot");

        tutorials.add(tut1);
        tutorials.add(tut2);
        return tutorials;
    }
}

  1. 添加配置Configuration
  • @EnableWs:提供spring web service 配置
  • 我们用@Bean(name=“tutorialService”)定义DefaultWsdl11Definition。tutorialService将是URL中WSDL的名称
  • wsdl11Definition.setWsdl,提示wsdl的本地
  • MessageDispatcherServlet将用于处理http请求
  • 需要设置ApplicationContext
  • servlet RegistrationBean将所有具有URI" /wsdlfirst/* "的传入请求映射到servlet
  • wsdl的url将是:http://localhost:8080/wsdlfirst/tutorialService.wsdl
package com.ping.wsdl.config;

import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.ws.config.annotation.EnableWs;
import org.springframework.ws.config.annotation.WsConfigurerAdapter;
import org.springframework.ws.transport.http.MessageDispatcherServlet;
import org.springframework.ws.wsdl.wsdl11.SimpleWsdl11Definition;
import org.springframework.ws.wsdl.wsdl11.Wsdl11Definition;

@EnableWs
@Configuration
public class WebServiceConfig extends WsConfigurerAdapter{
    
    

    @Bean
    public ServletRegistrationBean messageDispatcherServlet(ApplicationContext applicationContext) {
    
    
        MessageDispatcherServlet servlet = new MessageDispatcherServlet();
        servlet.setApplicationContext(applicationContext);
        return new ServletRegistrationBean(servlet, "/wsdlfirst/*");
    }

    @Bean(name="tutorialService")
    public Wsdl11Definition defaultWsdl11Definition() {
    
    
        SimpleWsdl11Definition wsdl11Definition = new SimpleWsdl11Definition();
        wsdl11Definition.setWsdl(new ClassPathResource("/wsdl/TutorialService.wsdl"));
        return wsdl11Definition;
    }
}

  1. 启动项目
package com.ping.wsdl;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class WsdlApplication {
    
    

    public static void main(String[] args) {
    
    
        SpringApplication.run(WsdlApplication.class, args);
    }

}

  1. 使用 soapUI 进行测试
  • 首先在soap UI导入准备好的wsdl文件
  • 然后在xml中输入需要的数据,执行即可获取响应的xml
    在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_43952429/article/details/132021753