• SpringBoot整合WebService


    文件:https://github.com/xiaozhengyu/SpringBoot.git

    WebService远程服务端

    1、新建工程service,最终工程如下:


    2、添加依赖包,pom.xml内容如下:

     1 <?xml version="1.0" encoding="UTF-8"?>
     2 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     3          xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
     4     <modelVersion>4.0.0</modelVersion>
     5     <parent>
     6         <groupId>org.springframework.boot</groupId>
     7         <artifactId>spring-boot-starter-parent</artifactId>
     8         <version>2.2.5.RELEASE</version>
     9         <relativePath/> <!-- lookup parent from repository -->
    10     </parent>
    11     <groupId>com.example.webservice</groupId>
    12     <artifactId>demo</artifactId>
    13     <version>0.0.1-SNAPSHOT</version>
    14     <name>service</name>
    15     <description>Demo project for Spring Boot</description>
    16 
    17     <properties>
    18         <java.version>1.8</java.version>
    19     </properties>
    20 
    21     <dependencies>
    22         <dependency>
    23             <groupId>org.springframework.boot</groupId>
    24             <artifactId>spring-boot-starter-web</artifactId>
    25         </dependency>
    26         <dependency>
    27             <groupId>org.springframework.boot</groupId>
    28             <artifactId>spring-boot-starter-web-services</artifactId>
    29         </dependency>
    30 
    31         <dependency>
    32             <groupId>org.springframework.boot</groupId>
    33             <artifactId>spring-boot-devtools</artifactId>
    34             <scope>runtime</scope>
    35             <optional>true</optional>
    36         </dependency>
    37         <dependency>
    38             <groupId>org.springframework.boot</groupId>
    39             <artifactId>spring-boot-configuration-processor</artifactId>
    40             <optional>true</optional>
    41         </dependency>
    42         <dependency>
    43             <groupId>org.projectlombok</groupId>
    44             <artifactId>lombok</artifactId>
    45             <optional>true</optional>
    46         </dependency>
    47         <dependency>
    48             <groupId>org.springframework.boot</groupId>
    49             <artifactId>spring-boot-starter-test</artifactId>
    50             <scope>test</scope>
    51             <exclusions>
    52                 <exclusion>
    53                     <groupId>org.junit.vintage</groupId>
    54                     <artifactId>junit-vintage-engine</artifactId>
    55                 </exclusion>
    56             </exclusions>
    57         </dependency>
    58 
    59         <!--json解析-->
    60         <dependency>
    61             <groupId>com.alibaba</groupId>
    62             <artifactId>fastjson</artifactId>
    63         </dependency>
    64         <dependency>
    65             <groupId>net.sf.json-lib</groupId>
    66             <artifactId>json-lib</artifactId>
    67             <version>2.4</version>
    68             <classifier>jdk15</classifier>
    69         </dependency>
    70         <!--webservice依赖-->
    71         <dependency>
    72             <groupId>org.apache.cxf</groupId>
    73             <artifactId>cxf-spring-boot-starter-jaxws</artifactId>
    74             <version>3.2.6</version>
    75         </dependency>
    76     </dependencies>
    77 
    78     <build>
    79         <plugins>
    80             <plugin>
    81                 <groupId>org.springframework.boot</groupId>
    82                 <artifactId>spring-boot-maven-plugin</artifactId>
    83             </plugin>
    84         </plugins>
    85     </build>
    86 
    87 </project>

    3、实体类代码如下:

     1 package com.example.webservice.demo.entity;
     2 
     3 import lombok.Data;
     4 
     5 /**
     6  * @author xzy
     7  * @date 2020-03-15 18:24
     8  * 说明:学生表对应的实体类
     9  */
    10 @Data
    11 public class StudentEntity {
    12     private String name;
    13     private Integer age;
    14 
    15     public StudentEntity(String name, Integer age) {
    16         this.name = name;
    17         this.age = age;
    18     }
    19 
    20     public StudentEntity() {
    21     }
    22 }
     1 package com.example.webservice.demo.entity;
     2 
     3 import lombok.Data;
     4 
     5 /**
     6  * @author xzy
     7  * @date 2020-03-15 18:25
     8  * 说明:user表对应的实体类
     9  */
    10 @Data
    11 public class UserEntity {
    12     private String name;
    13     private String sex;
    14 
    15     public UserEntity(String name, String sex) {
    16         this.name = name;
    17         this.sex = sex;
    18     }
    19 
    20     public UserEntity() {
    21     }
    22 }

    3、webservice接口及其实现类代码:

     1 package com.example.webservice.demo.service;
     2 
     3 import com.example.webservice.demo.entity.StudentEntity;
     4 
     5 import javax.jws.WebMethod;
     6 import javax.jws.WebService;
     7 import java.util.List;
     8 
     9 /**
    10  * @author xzy
    11  * @date 2020-03-15 18:26
    12  * 说明:
    13  * targetNamespace - 命名空间,写一个有意义的http地址就可以,写成包名的倒序是为了易于阅读。
    14  */
    15 @WebService(targetNamespace = "http://service.demo.webservice.example.com")
    16 public interface StudentService {
    17     /**
    18      * 获取所有学生信息
    19      *
    20      * @return - 所有学生信息
    21      */
    22     @WebMethod
    23     List<StudentEntity> getAll();
    24 }
     1 package com.example.webservice.demo.service;
     2 
     3 import com.example.webservice.demo.entity.UserEntity;
     4 
     5 import javax.jws.WebMethod;
     6 import javax.jws.WebParam;
     7 import javax.jws.WebService;
     8 import java.util.List;
     9 
    10 /**
    11  * @author xzy
    12  * @date 2020-03-15 18:26
    13  * 说明:对外提供的用户信息服务
    14  */
    15 @WebService(targetNamespace = "http://service.demo.webservice.example.com")
    16 public interface UserService {
    17     /**
    18      * 获取所有用户信息
    19      *
    20      * @return - 所有用户信息
    21      */
    22     @WebMethod
    23     List<UserEntity> getAllUser();
    24 
    25     /**
    26      * 根据用户名获取用户信息
    27      *
    28      * @param username - 用户名
    29      * @return - 用户信息
    30      */
    31     @WebMethod
    32     UserEntity getUserByName(@WebParam(name = "username") String username);
    33 }
     1 package com.example.webservice.demo.serviceimpl;
     2 
     3 import com.example.webservice.demo.entity.StudentEntity;
     4 import com.example.webservice.demo.service.StudentService;
     5 import org.springframework.stereotype.Service;
     6 
     7 import javax.jws.WebService;
     8 import java.util.ArrayList;
     9 import java.util.List;
    10 
    11 /**
    12  * @author xzy
    13  * @date 2020-03-15 20:01
    14  * 说明:对外提供的学生信息服务
    15  */
    16 @WebService(serviceName = "StudentService",
    17         targetNamespace = "http://service.demo.webservice.example.com",
    18         endpointInterface = "com.example.webservice.demo.service.StudentService")
    19 @Service
    20 public class StudentServiceImpl implements StudentService {
    21     /**
    22      * 获取所有学生信息
    23      *
    24      * @return - 所有学生信息
    25      */
    26     @Override
    27     public List<StudentEntity> getAll() {
    28         System.out.println("getAll():监听到请求");
    29         List<StudentEntity> students = new ArrayList<>();
    30         StudentEntity student1 = new StudentEntity("zhangsan", 20);
    31         StudentEntity student2 = new StudentEntity("lisi", 21);
    32         students.add(student1);
    33         students.add(student2);
    34         return students;
    35     }
    36 }
     1 package com.example.webservice.demo.serviceimpl;
     2 
     3 import com.example.webservice.demo.entity.UserEntity;
     4 import com.example.webservice.demo.service.UserService;
     5 import org.springframework.stereotype.Service;
     6 
     7 import javax.jws.WebService;
     8 import java.util.ArrayList;
     9 import java.util.List;
    10 
    11 /**
    12  * @author xzy
    13  * @date 2020-03-15 20:02
    14  * 说明:
    15  */
    16 @WebService(serviceName = "UserService",
    17         targetNamespace = "http://service.demo.webservice.example.com",
    18         endpointInterface = "com.example.webservice.demo.service.UserService")
    19 @Service
    20 public class UserServiceImpl implements UserService {
    21     /**
    22      * 获取所有用户信息
    23      *
    24      * @return - 所有用户信息
    25      */
    26     @Override
    27     public List<UserEntity> getAllUser() {
    28         System.out.println("getAllUser():监听到请求");
    29         List<UserEntity> users = new ArrayList<>();
    30         UserEntity user1 = new UserEntity("wangwu", "f");
    31         UserEntity user2 = new UserEntity("xiaoyu", "m");
    32         users.add(user1);
    33         users.add(user2);
    34         return users;
    35     }
    36 
    37     /**
    38      * 根据用户名获取用户信息
    39      *
    40      * @param username - 用户名
    41      * @return - 用户信息
    42      */
    43     @Override
    44     public UserEntity getUserByName(String username) {
    45         System.out.println("getUserByName():监听到请求,参数username = " + username);
    46         if ("张三".equals(username)) {
    47             return new UserEntity("张三", "m");
    48         } else {
    49             return new UserEntity("helloWorld", "!");
    50         }
    51     }
    52 }

    3、发布WebService

     1 package com.example.webservice.demo.config;
     2 
     3 import com.example.webservice.demo.service.StudentService;
     4 import com.example.webservice.demo.service.UserService;
     5 import org.apache.cxf.Bus;
     6 import org.springframework.beans.factory.annotation.Autowired;
     7 import org.springframework.context.annotation.Bean;
     8 import org.springframework.context.annotation.Configuration;
     9 import org.apache.cxf.jaxws.EndpointImpl;
    10 
    11 import javax.xml.ws.Endpoint;
    12 
    13 /**
    14  * @author xzy
    15  * @date 2020-03-15 17:49
    16  * 说明:服务端发布相关接口
    17  */
    18 @Configuration
    19 public class WebConfig {
    20     private Bus bus;
    21     private StudentService studentService;
    22     private UserService userService;
    23 
    24     @Autowired
    25     private void dependenceInject(Bus bus, StudentService studentService, UserService userService) {
    26         this.bus = bus;
    27         this.studentService = studentService;
    28         this.userService = userService;
    29     }
    30 
    31     @Bean
    32     public Endpoint endpointStudentService() {
    33         EndpointImpl endpoint = new EndpointImpl(bus, studentService);
    34         //接口发布在 /StudentService下
    35         endpoint.publish("/StudentService");
    36         return endpoint;
    37     }
    38 
    39     @Bean
    40     public Endpoint endpointUserService() {
    41         EndpointImpl endpoint = new EndpointImpl(bus, userService);
    42         endpoint.publish("/UserService");
    43         return endpoint;
    44     }
    45 }

     4、启动服务端


    5、查看webservice是否部署成功 


    点击 {http://service.demo.webservice.example.com}StudentService,查看到以下内容:

     1 This XML file does not appear to have any style information associated with it. The document tree is shown below.
     2 <wsdl:definitions xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:tns="http://service.demo.webservice.example.com" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:ns1="http://schemas.xmlsoap.org/soap/http" name="StudentService" targetNamespace="http://service.demo.webservice.example.com">
     3     <wsdl:types>
     4         <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:tns="http://service.demo.webservice.example.com" elementFormDefault="unqualified" targetNamespace="http://service.demo.webservice.example.com" version="1.0">
     5             <xs:element name="getAll" type="tns:getAll"/>
     6             <xs:element name="getAllResponse" type="tns:getAllResponse"/>
     7             <xs:complexType name="getAll">
     8                 <xs:sequence/>
     9             </xs:complexType>
    10             <xs:complexType name="getAllResponse">
    11                 <xs:sequence>
    12                     <xs:element maxOccurs="unbounded" minOccurs="0" name="return" type="tns:studentEntity"/>
    13                 </xs:sequence>
    14             </xs:complexType>
    15             <xs:complexType name="studentEntity">
    16                 <xs:sequence>
    17                     <xs:element minOccurs="0" name="age" type="xs:int"/>
    18                     <xs:element minOccurs="0" name="name" type="xs:string"/>
    19                 </xs:sequence>
    20             </xs:complexType>
    21         </xs:schema>
    22     </wsdl:types>
    23     <wsdl:message name="getAllResponse">
    24         <wsdl:part element="tns:getAllResponse" name="parameters"> </wsdl:part>
    25     </wsdl:message>
    26     <wsdl:message name="getAll">
    27         <wsdl:part element="tns:getAll" name="parameters"> </wsdl:part>
    28     </wsdl:message>
    29     <wsdl:portType name="StudentService">
    30         <wsdl:operation name="getAll">
    31             <wsdl:input message="tns:getAll" name="getAll"> </wsdl:input>
    32             <wsdl:output message="tns:getAllResponse" name="getAllResponse"> </wsdl:output>
    33         </wsdl:operation>
    34     </wsdl:portType>
    35     <wsdl:binding name="StudentServiceSoapBinding" type="tns:StudentService">
    36         <soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>
    37         <wsdl:operation name="getAll">
    38             <soap:operation soapAction="" style="document"/>
    39             <wsdl:input name="getAll">
    40                 <soap:body use="literal"/>
    41             </wsdl:input>
    42             <wsdl:output name="getAllResponse">
    43                 <soap:body use="literal"/>
    44             </wsdl:output>
    45         </wsdl:operation>
    46     </wsdl:binding>
    47     <wsdl:service name="StudentService">
    48         <wsdl:port binding="tns:StudentServiceSoapBinding" name="StudentServiceImplPort">
    49             <soap:address location="http://127.0.0.1:1234/services/StudentService"/>
    50         </wsdl:port>
    51     </wsdl:service>
    52 </wsdl:definitions>

    客户端

    1、创建工程client,完整工程为:


    2、 添加依赖包,pom.xml文件与服务端相同。

    3、实现客户端调用webservice服务:

     1 package com.example.webservice.demo.serviceimpl;
     2 
     3 import net.sf.json.JSONArray;
     4 import org.apache.cxf.endpoint.Client;
     5 import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;
     6 
     7 import java.util.Arrays;
     8 
     9 
    10 /**
    11  * @author xzy
    12  * @date 2020-03-15 21:04
    13  * 说明:测试
    14  */
    15 public class Test {
    16     public static void main(String[] args) {
    17         //在一个方法中连续调用多次WebService接口,每次调用前需要重置上下文。
    18         ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    19         /*
    20          * --通过JaxWsDynamicClientFactory进行WebService客户端调用的一个好处就是,只需要知道了WSDL地址就行了,
    21          * 不需要手动生成任何代码,这样,如果需要调用多个WebService服务的话,只需要创建多个Client即可,不用
    22          * 考虑传统方式(生成代码)冲突问题,这样可以让代码更优雅。
    23          */
    24         JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
    25 
    26         printStudents(dcf);
    27 
    28         //在调用第二个webservice前,需要重置上下文
    29         Thread.currentThread().setContextClassLoader(classLoader);
    30 
    31         printUser(dcf);
    32     }
    33 
    34     /**
    35      * 调用远端WebService的服务,获取学生信息
    36      *
    37      * @param dcf - 用于远程webservice调用。
    38      */
    39     private static void printStudents(JaxWsDynamicClientFactory dcf) {
    40         Client client = dcf.createClient("http://127.0.0.1:1234/services/StudentService?wsdl");
    41 
    42         /*
    43          *--需要密码的情况需要添加上用户名和密码
    44          *client.getOutInterceptors().add(new ClientLoginInterceptor(USERNAME,PASSWORD));
    45          */
    46 
    47         try {
    48             //invoke("方法名",参数1,参数2,参数3......)
    49             Object students = client.invoke("getAll");
    50             JSONArray jsonArray = JSONArray.fromObject(students);
    51             System.out.println(Arrays.toString(jsonArray.toArray()));
    52         } catch (Exception e) {
    53             e.printStackTrace();
    54         }
    55 
    56     }
    57 
    58     /**
    59      * 调用远端WebService的服务,获取用户信息
    60      *
    61      * @param dcf - 用于远程webservice调用。
    62      */
    63     private static void printUser(JaxWsDynamicClientFactory dcf) {
    64         Client client = dcf.createClient("http://127.0.0.1:1234/services/UserService?wsdl");
    65 
    66         /*
    67          *--需要密码的情况需要添加上用户名和密码
    68          *client.getOutInterceptors().add(new ClientLoginInterceptor(USERNAME,PASSWORD));
    69          */
    70         try {
    71             /*
    72              *--invoke("方法名",参数1,参数2,参数3......),返回值Object[]
    73              *--invoke将请求拼接成xml发送给远端的WebService服务,接受对面返回的xml,取出返回值,填到一个Java对象返回。
    74              */
    75             Object user = client.invoke("getUserByName", "张三");
    76             JSONArray jsonArray = JSONArray.fromObject(user);
    77             System.out.println(Arrays.toString(jsonArray.toArray()));
    78         } catch (
    79                 Exception e) {
    80             e.printStackTrace();
    81         }
    82 
    83     }
    84 }

    4、执行代码

    客户端打印:

    [[{"age":20,"name":"zhangsan"},{"age":21,"name":"lisi"}]]

    服务端打印:

    getAll():监听到请求
    getUserByName():监听到请求,参数username = 张三
  • 相关阅读:
    跨域上传文件
    算法
    websocket
    Bottle
    爬虫一
    RabbitMQ
    git&github快速入门
    centos6安装SaltStack
    ajax
    Django之Model操作
  • 原文地址:https://www.cnblogs.com/XiaoZhengYu/p/12501404.html
Copyright © 2020-2023  润新知