SpringBoot整合WebService

这篇具有很好参考价值的文章主要介绍了SpringBoot整合WebService。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

SpringBoot整合WebService

WebService是一个比较旧的远程调用通信框架,现在企业项目中用的比较少,因为它逐步被SpringCloud所取代,它的优势就是能够跨语言平台通信,所以还有点价值,下面来看看如何在SpringBoot项目中使用WebService

我们模拟从WebService客户端发送请求给WebService服务端暴露的下载文件服务,并获取服务端返回的文件保存到本地

环境

SpringBoot2.7.3

Jdk17

服务端

在SpringBoot中整合WebService的服务端,需要通过一个配置文件将服务接口暴露出去给客户端调用

项目结构

SpringBoot整合WebService,SpringBoot,spring boot,后端,java

配置

服务端POM

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.3</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>webservice</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>webservice</name>
    <description>webservice</description>
    <properties>
        <java.version>17</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!--cxf-->
        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-rt-transports-http</artifactId>
            <version>3.5.1</version>
        </dependency>

        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-rt-frontend-jaxws</artifactId>
            <version>3.5.1</version>
        </dependency>

        <!--hutool-->
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.8.12</version>
        </dependency>

        <!--fastjson-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>2.0.16</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

服务端YML

server: # 必须配置端口,客户端需要
  port: 7001

FileCxfConfig

该文件为WebService服务暴露配置文件

package com.example.webservice.config;

import com.example.webservice.service.FileCxfService;
import com.example.webservice.service.impl.FileCxfServiceImpl;
import org.apache.cxf.Bus;
import org.apache.cxf.bus.spring.SpringBus;
import org.apache.cxf.jaxws.EndpointImpl;
import org.apache.cxf.transport.servlet.CXFServlet;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.xml.ws.Endpoint;

@Configuration
public class FileCxfConfig {

    @Bean(name = Bus.DEFAULT_BUS_ID)
    public SpringBus springBus() {
        return new SpringBus();
    }

    @Bean(name = "downloadFileBean")
    public ServletRegistrationBean dispatcherServlet() {
        ServletRegistrationBean wbsServlet = new ServletRegistrationBean(new CXFServlet(), "/file/*");
        return wbsServlet;
    }

    @Bean
    public FileCxfService fileCxfService() {
        return new FileCxfServiceImpl();
    }

    @Bean
    public Endpoint endpointPurchase(SpringBus springBus, FileCxfService fileCxfService) {
        EndpointImpl endpoint = new EndpointImpl(springBus(), fileCxfService());
        endpoint.publish("/download");
        System.err.println("服务发布成功!地址为:http://localhost:7001/file/download?wsdl");
        return endpoint;
    }
    
}

FileCxfService

该类指定了暴露的服务接口,注意类中的注解都很重要,不能丢,具体可以看说明

package com.example.webservice.service;


import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;
import javax.xml.ws.BindingType;

@BindingType(value = "http://www.w3.org/2003/05/soap/bindings/HTTP/")
@WebService(serviceName = "FileCxfService", // 与接口中指定的name一致
        targetNamespace = "http://webservice.example.com" // 与接口中的命名空间一致,一般是接口的包名倒
)
public interface FileCxfService {

    @WebMethod(operationName = "downloadFile")
    @WebResult(name = "String")
    String downloadFile(@WebParam(name = "params", targetNamespace = "http://webservice.example.com") String params,
                @WebParam(name = "token", targetNamespace = "http://webservice.example.com") String token);

}

FileCxfServiceImpl

该类指定了暴露的服务接口的具体实现,注意类中的注解都很重要,不能丢,具体可以看说明

package com.example.webservice.service.impl;

import cn.hutool.core.codec.Base64;
import com.alibaba.fastjson2.JSONObject;
import com.example.webservice.pojo.FileDto;
import com.example.webservice.service.FileCxfService;

import javax.jws.WebService;

@WebService(serviceName = "FileCxfService", // 与接口中指定的name一致
        targetNamespace = "http://webservice.example.com" // 与接口中的命名空间一致,一般是接口的包名倒
)
public class FileCxfServiceImpl implements FileCxfService {

    @Override
    public String downloadFile(String params, String token) {
        //下载文件
        System.err.println("params : " + params);
        FileDto fileDto = JSONObject.parseObject(params, FileDto.class);
        System.err.println("fileDto : " + fileDto);
        String data = null;
        try {
            data = Base64.encode("C:\\Users\\YIQI\\Desktop\\ebook\\Java70.pdf");
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.err.println(data);
        return data;
    }

}

FileDto

该类为参数实体类,用于接受客户端传来的参数

package com.example.webservice.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.ToString;

@Data
@AllArgsConstructor
@ToString
public class FileDto {

    private String fileId;
    private String newFileId;
    private String bucketName;

}

客户端

在SpringBoot中整合WebService的客户端,需要指定服务端暴露的服务接口

项目结构

SpringBoot整合WebService,SpringBoot,spring boot,后端,java

配置

客户端POM

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.3</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>webclient</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>webclient</name>
    <description>webclient</description>
    <properties>
        <java.version>17</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!--cxf-->
        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-rt-transports-http</artifactId>
            <version>3.5.1</version>
        </dependency>

        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-rt-frontend-jaxws</artifactId>
            <version>3.5.1</version>
        </dependency>

        <!--hutool-->
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.8.12</version>
        </dependency>

        <!--fastjson-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>2.0.16</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

客户端YML

server: # 可以不配置
  port: 1000

FileCxfService

这个文件和服务端的FileCxfService保持一致,用于指定客户端请求的方式

package com.example.webclient.service;


import javax.jws.WebParam;
import javax.jws.WebService;

@WebService(name = "FileCxfService", // 暴露服务名称
        targetNamespace = "http://webservice.example.com"// 命名空间,一般是接口的包名倒序
)
public interface FileCxfService {

    String downloadFile(@WebParam(name = "data", targetNamespace = "http://webservice.example.com") String data,
                @WebParam(name = "token", targetNamespace = "http://webservice.example.com") String token);

}

FileCxfClient

这个类是客户端的主类,里面有发送WebService请求的方法

package com.example.webclient.client;

import cn.hutool.core.codec.Base64;
import com.alibaba.fastjson2.JSONObject;
import com.example.webclient.pojo.FileDto;
import com.example.webclient.service.FileCxfService;
import com.example.webclient.util.ConvertBASE64;

import javax.xml.bind.DatatypeConverter;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;
import java.net.URL;


public class FileCxfClient {

    public static void main(String[] args) throws Exception {

        // 创建wsdl的url
        URL url = new URL("http://localhost:7001/file/download?wsdl");
        // 指定命名空间和服务名称
        QName qName = new QName("http://webservice.example.com", "FileCxfService");
        Service service = Service.create(url, qName);
        // 通过getPort方法返回指定接口
        FileCxfService myServer = service.getPort(FileCxfService.class);
        // 调用方法返回数据
        FileDto fileDto = new FileDto();
        fileDto.setFileId("1");
        fileDto.setNewFileId("1");
        fileDto.setBucketName("book");
        String params = JSONObject.toJSONString(fileDto);
        Long st = System.currentTimeMillis();
        String file = myServer.downloadFile(params, "TOKEN:ABC");
        // 解析文件到本地
        // 可以解析成字节数组,如果服务端返回的也是字节数组的话
        byte[] decode= Base64.decode(file);
        // 也可以将Base64写入到本地文件中
        ConvertBASE64.decoderBase64File(file, "C:\\Users\\YIQI\\Desktop\\ebook\\demo70.pdf");
        System.err.println("decode : " + decode.toString());
        System.err.println("result get file success!");
        System.err.println("cost time : " + (System.currentTimeMillis() - st) / 1000 + " s.");

    }

}

FileDto

这个类是封装请求参数的实体类,和服务端的FileDto保持一致

package com.example.webclient.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;

@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class FileDto {

    private String fileId;
    private String newFileId;
    private String bucketName;

}

ConvertBASE64

该类是Base64工具类,可以完成Base64字符串和文件的互换

package com.example.webclient.util;


import cn.hutool.core.codec.Base64Decoder;
import cn.hutool.core.codec.Base64Encoder;
import cn.hutool.core.io.FileUtil;
import com.alibaba.fastjson2.JSONObject;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class ConvertBASE64 {

    /**
     * 将文件转成base64编码字符串
     *
     * @param path
     * @return
     * @throws Exception
     */
    public static String encodeBase64File(String path) throws Exception {
        File file = new File(path);
        FileInputStream inputFile = new FileInputStream(file);
        byte[] buffer = new byte[(int) file.length()];
        inputFile.read(buffer);
        inputFile.close();
        return new Base64Encoder().encode(buffer);
    }


    /**
     * 将base64编码字符串转成文件
     *
     * @param base64Code
     * @param targetPath
     * @throws Exception
     */
    public static void decoderBase64File(String base64Code, String targetPath)
            throws Exception {
        byte[] buffer = Base64Decoder.decode(base64Code);
        FileOutputStream out = new FileOutputStream(targetPath);
        out.write(buffer);
        out.close();
    }


    /**
     * 将base64字节装成文件
     *
     * @param base64Code
     * @param targetPath
     * @throws Exception
     */
    public static void toFile(String base64Code, String targetPath)
            throws Exception {
        byte[] buffer = base64Code.getBytes();
        FileOutputStream out = new FileOutputStream(targetPath);
        out.write(buffer);
        out.close();
    }


    public static String toJson(Object obj) {
        return JSONObject.toJSONString(obj);
    }


    public static Object toObject(String JSONString, Class cls) {
        return JSONObject.parseObject(JSONString, cls);
    }


    public static void writeByteArrayToFile(File desFile, byte[] data)
            throws IOException {
        FileUtil.writeBytes(data, desFile);
    }


    public static byte[] readFileToByteArray(File srcFile)
            throws IOException {
        return FileUtil.readBytes(srcFile);
    }


    public static String encode(String string) {
        return new String(Base64Encoder.encode(string.getBytes()));

    }


    public static void main(String[] args) {
        try {
            String a = encodeBase64File("C:\\Users\\YIQI\\Desktop\\工作文件\\bg2.jpg");
            // String base64Code = encodeBase64File("D:/0101-2011-qqqq.tif");
            System.out.println(a);
            decoderBase64File(a, "C:\\Users\\YIQI\\Desktop\\工作文件\\bg3.jpg");
            // toFile(base64Code, "D:\\three.txt");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

测试

先启动服务端,可以看到对外发布的服务

SpringBoot整合WebService,SpringBoot,spring boot,后端,java

在启动客户端给服务端发送请求的方法,可以看到服务端返回的数据

SpringBoot整合WebService,SpringBoot,spring boot,后端,java

因为我把从服务端获取的文件写入到了本地,所以可以在文件目录中看到该文件

SpringBoot整合WebService,SpringBoot,spring boot,后端,java文章来源地址https://www.toymoban.com/news/detail-613193.html

到了这里,关于SpringBoot整合WebService的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • [webservice] springboot整合cxf

    2.1 pom.xml 中添加依赖 springboot整合Apache cxf 2.3 service发布(cxf配置) 发布完成后启动web服务,可以通过: http://127.0.0.1:8080/ws 访问已经发布的服务。 在这里分享一个天气预报的webservice服务: http://www.webxml.com.cn/WebServices/WeatherWebService.asmx?wsdl 3.1 使用wsdl2java生成webservice客户端代码

    2024年04月25日
    浏览(21)
  • 【Spring Boot】SpringBoot 优雅整合Swagger Api 自动生成文档

    Swagger 是一套 RESTful API 文档生成工具,可以方便地生成 API 文档并提供 API 调试页面。 而 Spring Boot 是一款非常优秀的 Java Web 开发框架,它可以非常方便地构建 Web 应用程序。 在本文中,我们将介绍如何使用 Swagger 以及如何在 Spring Boot 中整合 Swagger 。 首先,在 pom.xml 文件中添

    2023年04月22日
    浏览(34)
  • SpringBoot + Vue前后端分离项目实战 || 三:Spring Boot后端与Vue前端连接

    系列文章: SpringBoot + Vue前后端分离项目实战 || 一:Vue前端设计 SpringBoot + Vue前后端分离项目实战 || 二:Spring Boot后端与数据库连接 SpringBoot + Vue前后端分离项目实战 || 三:Spring Boot后端与Vue前端连接 SpringBoot + Vue前后端分离项目实战 || 四:用户管理功能实现 SpringBoot + Vue前后

    2024年02月12日
    浏览(56)
  • SpringBoot + Vue前后端分离项目实战 || 二:Spring Boot后端与数据库连接

    系列文章: SpringBoot + Vue前后端分离项目实战 || 一:Vue前端设计 SpringBoot + Vue前后端分离项目实战 || 二:Spring Boot后端与数据库连接 SpringBoot + Vue前后端分离项目实战 || 三:Spring Boot后端与Vue前端连接 SpringBoot + Vue前后端分离项目实战 || 四:用户管理功能实现 SpringBoot + Vue前后

    2024年02月11日
    浏览(50)
  • spring-boot webservice的例子

    源码下载地址 spring-boot-webservice例子资源-CSDN文库 源码下载地址 spring-boot-clintwebservice调用服务的例子资源-CSDN文库

    2024年02月14日
    浏览(38)
  • spring boot es | spring boot 整合elasticsearch | spring boot整合多数据源es

    目录 Spring Boot与ES版本对应 Maven依赖 配置类 使用方式 @Test中注入方式 @Component中注入方式 查询文档 实体类 通过ElasticsearchRestTemplate查询 通过JPA查询 保存文档 参考链接 项目组件版本: Spring Boot:2.2.13.RELEASE Elasticsearch:6.8.0 JDK:1.8.0_66 Tips: 主要看第3列和第5列,根据ES版本选择

    2023年04月18日
    浏览(43)
  • 【Spring Boot】Spring Boot整合多数据源

    在实际的开发工作中,我们经常会遇到需要整合多个数据源的情况,比如同时连接多个数据库、读写分离、跨数据库查询等。本文将介绍如何使用Spring Boot来实现多数据源的整合,对于刚刚接触开发的小伙伴可能有一些帮助。 在一个应用程序中使用多个数据源意味着我们需要

    2024年02月10日
    浏览(33)
  • 六、Spring/Spring Boot整合ActiveMQ

    2.1 applicationContext.xml 路径:src/main/resources/applicationContext.xml 2.2 生产者 2.3 消费者 3.1 applicationContext.xml 路径:src/main/resources/applicationContext.xml 3.2 生产者 和队列的代码一样,只是在配置文件里面改了destination 3.3 消费者 和队列的代码一样,只是在配置文件里面改了destination 实现

    2024年02月22日
    浏览(34)
  • Spring Boot进阶(96):轻松上手:实战Spring Boot整合Docker

      Docker 是一个开源的应用程序容器化工具,它可以将应用程序和依赖组件打包到一个容器中,实现应用程序的快速部署和运行。Spring Boot 是一个快速开发应用程序的框架,使用 Spring Boot 可以快速构建各种各样的应用程序。本文将介绍如何使用 Spring Boot 整合 Docker,实现应用

    2024年02月07日
    浏览(40)
  • Spring Boot整合Junit

    2024年01月17日
    浏览(25)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包