search
HomeJavajavaTutorialHow does SpringBoot integrate SFTP client to upload and download files?

Background

In project development, SFTP services are rarely used for general file storage, but it is not ruled out that partners use SFTP to store files in the project or implement file data interaction through SFTP.

In the projects I have encountered, partners such as banks and insurance companies use SFTP services to interact with the file data of our projects.

In order to successfully connect to the SFTP service of our friends, we need to implement a set of SFTP client tools in our own project. Generally we will use Jsch to implement the SFTP client.

Dependency

<!--执行远程操作-->
<dependency>
    <groupId>com.jcraft</groupId>
    <artifactId>jsch</artifactId>
    <version>0.1.55</version>
</dependency>
     <!--链接池-->
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-pool2</artifactId>
    <version>2.11.1</version>
</dependency>

First of all, we must introduce the jsch dependency, which is the cornerstone of our implementation of the SFTP client; secondly, we introduce the connection pool tool, in order to avoid executing it every time All SFTP commands require re-creating the link. We use pooling to optimize the resource-intensive creation operation.

Create tool class

In order to better use the SFTP tool, we extracted the related functions of SFTP in jsch and made a simple encapsulation into There are tool classes that we can use directly.

There are only two types of methods:

1. Create Session and open Session;

After the session is created, the channel cannot be created. You need to open the session before you can create the channel;

2. Create channel and open channel;

The same is true for channel. The created channel needs to be opened before the command can be actually executed;

public class JschUtil {
  /**
   * 创建session
   *
   * @param userName       用户名
   * @param password       密码
   * @param host           域名
   * @param port           端口
   * @param privateKeyFile 密钥文件
   * @param passphrase     口令
   * @return
   * @throws AwesomeException
   */
  public static Session createSession(String userName, String password, String host, int port, String privateKeyFile, String passphrase) throws AwesomeException {
    return createSession(new JSch(), userName, password, host, port, privateKeyFile, passphrase);
  }
  /**
   * 创建session
   *
   * @param jSch
   * @param userName       用户名
   * @param password       密码
   * @param host           域名
   * @param port           端口
   * @param privateKeyFile 密钥
   * @param passphrase     口令
   * @return
   * @throws AwesomeException
   */
  public static Session createSession(JSch jSch, String userName, String password, String host, int port, String privateKeyFile, String passphrase) throws AwesomeException {
    try {
      if (!StringUtils.isEmpty(privateKeyFile)) {
        // 使用密钥验证方式,密钥可以是有口令的密钥,也可以是没有口令的密钥
        if (!StringUtils.isEmpty(passphrase)) {
          jSch.addIdentity(privateKeyFile, passphrase);
        } else {
          jSch.addIdentity(privateKeyFile);
        }
      }
      // 获取session
      Session session = jSch.getSession(userName, host, port);
      if (!StringUtils.isEmpty(password)) {
        session.setPassword(password);
      }
      // 不校验域名
      session.setConfig("StrictHostKeyChecking", "no");
      return session;
    } catch (Exception e) {
      throw new AwesomeException(500, "create session fail");
    }
  }
  /**
   * 创建session
   *
   * @param jSch
   * @param userName 用户名
   * @param password 密码
   * @param host     域名
   * @param port     端口
   * @return
   * @throws AwesomeException
   */
  public static Session createSession(JSch jSch, String userName, String password, String host, int port) throws AwesomeException {
    return createSession(jSch, userName, password, host, port, StringUtils.EMPTY, StringUtils.EMPTY);
  }
  /**
   * 创建session
   *
   * @param jSch
   * @param userName 用户名
   * @param host     域名
   * @param port     端口
   * @return
   * @throws AwesomeException
   */
  private Session createSession(JSch jSch, String userName, String host, int port) throws AwesomeException {
    return createSession(jSch, userName, StringUtils.EMPTY, host, port, StringUtils.EMPTY, StringUtils.EMPTY);
  }
  /**
   * 开启session链接
   *
   * @param jSch
   * @param userName       用户名
   * @param password       密码
   * @param host           域名
   * @param port           端口
   * @param privateKeyFile 密钥
   * @param passphrase     口令
   * @param timeout        链接超时时间
   * @return
   * @throws AwesomeException
   */
  public static Session openSession(JSch jSch, String userName, String password, String host, int port, String privateKeyFile, String passphrase, int timeout) throws AwesomeException {
    Session session = createSession(jSch, userName, password, host, port, privateKeyFile, passphrase);
    try {
      if (timeout >= 0) {
        session.connect(timeout);
      } else {
        session.connect();
      }
      return session;
    } catch (Exception e) {
      throw new AwesomeException(500, "session connect fail");
    }
  }
  /**
   * 开启session链接
   *
   * @param userName       用户名
   * @param password       密码
   * @param host           域名
   * @param port           端口
   * @param privateKeyFile 密钥
   * @param passphrase     口令
   * @param timeout        链接超时时间
   * @return
   * @throws AwesomeException
   */
  public static Session openSession(String userName, String password, String host, int port, String privateKeyFile, String passphrase, int timeout) throws AwesomeException {
    Session session = createSession(userName, password, host, port, privateKeyFile, passphrase);
    try {
      if (timeout >= 0) {
        session.connect(timeout);
      } else {
        session.connect();
      }
      return session;
    } catch (Exception e) {
      throw new AwesomeException(500, "session connect fail");
    }
  }
  /**
   * 开启session链接
   *
   * @param jSch
   * @param userName 用户名
   * @param password 密码
   * @param host     域名
   * @param port     端口
   * @param timeout  链接超时时间
   * @return
   * @throws AwesomeException
   */
  public static Session openSession(JSch jSch, String userName, String password, String host, int port, int timeout) throws AwesomeException {
    return openSession(jSch, userName, password, host, port, StringUtils.EMPTY, StringUtils.EMPTY, timeout);
  }
  /**
   * 开启session链接
   *
   * @param userName 用户名
   * @param password 密码
   * @param host     域名
   * @param port     端口
   * @param timeout  链接超时时间
   * @return
   * @throws AwesomeException
   */
  public static Session openSession(String userName, String password, String host, int port, int timeout) throws AwesomeException {
    return openSession(userName, password, host, port, StringUtils.EMPTY, StringUtils.EMPTY, timeout);
  }
  /**
   * 开启session链接
   *
   * @param jSch
   * @param userName 用户名
   * @param host     域名
   * @param port     端口
   * @param timeout  链接超时时间
   * @return
   * @throws AwesomeException
   */
  public static Session openSession(JSch jSch, String userName, String host, int port, int timeout) throws AwesomeException {
    return openSession(jSch, userName, StringUtils.EMPTY, host, port, StringUtils.EMPTY, StringUtils.EMPTY, timeout);
  }
  /**
   * 开启session链接
   *
   * @param userName 用户名
   * @param host     域名
   * @param port     端口
   * @param timeout  链接超时时间
   * @return
   * @throws AwesomeException
   */
  public static Session openSession(String userName, String host, int port, int timeout) throws AwesomeException {
    return openSession(userName, StringUtils.EMPTY, host, port, StringUtils.EMPTY, StringUtils.EMPTY, timeout);
  }
  /**
   * 创建指定通道
   *
   * @param session
   * @param channelType
   * @return
   * @throws AwesomeException
   */
  public static Channel createChannel(Session session, ChannelType channelType) throws AwesomeException {
    try {
      if (!session.isConnected()) {
        session.connect();
      }
      return session.openChannel(channelType.getValue());
    } catch (Exception e) {
      throw new AwesomeException(500, "open channel fail");
    }
  }
  /**
   * 创建sftp通道
   *
   * @param session
   * @return
   * @throws AwesomeException
   */
  public static ChannelSftp createSftp(Session session) throws AwesomeException {
    return (ChannelSftp) createChannel(session, ChannelType.SFTP);
  }
  /**
   * 创建shell通道
   *
   * @param session
   * @return
   * @throws AwesomeException
   */
  public static ChannelShell createShell(Session session) throws AwesomeException {
    return (ChannelShell) createChannel(session, ChannelType.SHELL);
  }
  /**
   * 开启通道
   *
   * @param session
   * @param channelType
   * @param timeout
   * @return
   * @throws AwesomeException
   */
  public static Channel openChannel(Session session, ChannelType channelType, int timeout) throws AwesomeException {
    Channel channel = createChannel(session, channelType);
    try {
      if (timeout >= 0) {
        channel.connect(timeout);
      } else {
        channel.connect();
      }
      return channel;
    } catch (Exception e) {
      throw new AwesomeException(500, "connect channel fail");
    }
  }
  /**
   * 开启sftp通道
   *
   * @param session
   * @param timeout
   * @return
   * @throws AwesomeException
   */
  public static ChannelSftp openSftpChannel(Session session, int timeout) throws AwesomeException {
    return (ChannelSftp) openChannel(session, ChannelType.SFTP, timeout);
  }
  /**
   * 开启shell通道
   *
   * @param session
   * @param timeout
   * @return
   * @throws AwesomeException
   */
  public static ChannelShell openShellChannel(Session session, int timeout) throws AwesomeException {
    return (ChannelShell) openChannel(session, ChannelType.SHELL, timeout);
  }
  enum ChannelType {
    SESSION("session"),
    SHELL("shell"),
    EXEC("exec"),
    X11("x11"),
    AGENT_FORWARDING("auth-agent@openssh.com"),
    DIRECT_TCPIP("direct-tcpip"),
    FORWARDED_TCPIP("forwarded-tcpip"),
    SFTP("sftp"),
    SUBSYSTEM("subsystem");
    private final String value;
    ChannelType(String value) {
      this.value = value;
    }
    public String getValue() {
      return this.value;
    }
  }
}

We pool channels ChannelSftp by implementing the BasePooledObjectFactory class. This is not the actual pooling code, the following code just tells the pool manager how to create and destroy objects.

static class SftpFactory extends BasePooledObjectFactory<ChannelSftp> implements AutoCloseable {
    private Session session;
    private SftpProperties properties;
    // 初始化SftpFactory
    // 里面主要是创建目标session,后续可用通过这个session不断地创建ChannelSftp。
    SftpFactory(SftpProperties properties) throws AwesomeException {
      this.properties = properties;
      String username = properties.getUsername();
      String password = properties.getPassword();
      String host = properties.getHost();
      int port = properties.getPort();
      String privateKeyFile = properties.getPrivateKeyFile();
      String passphrase = properties.getPassphrase();
      session = JschUtil.createSession(username, password, host, port, privateKeyFile, passphrase);
    }
    // 销毁对象,主要是销毁ChannelSftp
    @Override
    public void destroyObject(PooledObject<ChannelSftp> p) throws Exception {
      p.getObject().disconnect();
    }
    // 创建对象ChannelSftp
    @Override
    public ChannelSftp create() throws Exception {
      int timeout = properties.getTimeout();
      return JschUtil.openSftpChannel(this.session, timeout);
    }
    // 包装创建出来的对象
    @Override
    public PooledObject<ChannelSftp> wrap(ChannelSftp channelSftp) {
      return new DefaultPooledObject<>(channelSftp);
    }
    // 验证对象是否可用
    @Override
    public boolean validateObject(PooledObject<ChannelSftp> p) {
      return p.getObject().isConnected();
    }
    // 销毁资源,关闭session
    @Override
    public void close() throws Exception {
      if (Objects.nonNull(session)) {
        if (session.isConnected()) {
          session.disconnect();
        }
        session = null;
      }
    }
  }

In order to realize the real pooling operation, we also need the following code:

1. We need to create a GenericObjectPool object pool in the SftpClient object. This is The real pool, which is responsible for creating and storing all objects.

2. We also need to provide the function of resource destruction, that is, to implement AutoCloseable. When the service stops, the relevant resources need to be destroyed.

public class SftpClient implements AutoCloseable {
  private SftpFactory sftpFactory;
  GenericObjectPool<ChannelSftp> objectPool;
  // 构造方法1
  public SftpClient(SftpProperties properties, GenericObjectPoolConfig<ChannelSftp> poolConfig) throws AwesomeException {
    this.sftpFactory = new SftpFactory(properties);
    objectPool = new GenericObjectPool<>(this.sftpFactory, poolConfig);
  }
  // 构造方法2
  public SftpClient(SftpProperties properties) throws AwesomeException {
    this.sftpFactory = new SftpFactory(properties);
    SftpProperties.PoolConfig config = properties.getPool();
    // 默认池化配置
    if (Objects.isNull(config)) {
      objectPool = new GenericObjectPool<>(this.sftpFactory);
    } else {
      // 自定义池化配置
      GenericObjectPoolConfig<ChannelSftp> poolConfig = new GenericObjectPoolConfig<>();
      poolConfig.setMaxIdle(config.getMaxIdle());
      poolConfig.setMaxTotal(config.getMaxTotal());
      poolConfig.setMinIdle(config.getMinIdle());
      poolConfig.setTestOnBorrow(config.isTestOnBorrow());
      poolConfig.setTestOnCreate(config.isTestOnCreate());
      poolConfig.setTestOnReturn(config.isTestOnReturn());
      poolConfig.setTestWhileIdle(config.isTestWhileIdle());
      poolConfig.setBlockWhenExhausted(config.isBlockWhenExhausted());
      poolConfig.setMaxWait(Duration.ofMillis(config.getMaxWaitMillis()));
      poolConfig.setTimeBetweenEvictionRuns(Duration.ofMillis(config.getTimeBetweenEvictionRunsMillis()));
      objectPool = new GenericObjectPool<>(this.sftpFactory, poolConfig);
    }
  }
  
  // 销毁资源
    @Override
  public void close() throws Exception {
    // 销毁链接池
    if (Objects.nonNull(this.objectPool)) {
      if (!this.objectPool.isClosed()) {
        this.objectPool.close();
      }
    }
    this.objectPool = null;
    // 销毁sftpFactory
    if (Objects.nonNull(this.sftpFactory)) {
      this.sftpFactory.close();
    }
  }
}

We have initialized the link pool. Now we can get the ChannelSftp we need from the link pool to implement the file. Uploaded and downloaded.

The following implements a variety of file upload and download methods:

1. Directly upload local files to the specified path of the SFTP server;

2. Input the InputStream into the stream Submit to the path specified by the SFTP server;

3. You can monitor the progress of the above two upload methods;

4. Download the specified file in the SFTP server to the local machine;

5. Write the files in the SFTP server to the specified output stream;

6. Monitor the download progress for the above two download methods;

  /**
   * 上传文件
   *
   * @param srcFilePath
   * @param targetDir
   * @param targetFileName
   * @return
   * @throws AwesomeException
   */
  public boolean uploadFile(String srcFilePath, String targetDir, String targetFileName) throws AwesomeException {
    return uploadFile(srcFilePath, targetDir, targetFileName, null);
  }
  /**
   * 上传文件
   *
   * @param srcFilePath
   * @param targetDir
   * @param targetFileName
   * @param monitor
   * @return
   * @throws AwesomeException
   */
  public boolean uploadFile(String srcFilePath, String targetDir, String targetFileName, SftpProgressMonitor monitor) throws AwesomeException {
    ChannelSftp channelSftp = null;
    try {
      // 从链接池获取对象
      channelSftp = this.objectPool.borrowObject();
      // 如果不存在目标文件夹
      if (!exist(channelSftp, targetDir)) {
        mkdirs(channelSftp, targetDir);
      }
      channelSftp.cd(targetDir);
      // 上传文件
      if (Objects.nonNull(monitor)) {
        channelSftp.put(srcFilePath, targetFileName, monitor);
      } else {
        channelSftp.put(srcFilePath, targetFileName);
      }
      return true;
    } catch (Exception e) {
      throw new AwesomeException(500, "upload file fail");
    } finally {
      if (Objects.nonNull(channelSftp)) {
        // 返还对象给链接池
        this.objectPool.returnObject(channelSftp);
      }
    }
  }
  /**
   * 上传文件到目标文件夹
   *
   * @param in
   * @param targetDir
   * @param targetFileName
   * @return
   * @throws AwesomeException
   */
  public boolean uploadFile(InputStream in, String targetDir, String targetFileName) throws AwesomeException {
    return uploadFile(in, targetDir, targetFileName, null);
  }
  /**
   * 上传文件,添加进度监视器
   *
   * @param in
   * @param targetDir
   * @param targetFileName
   * @param monitor
   * @return
   * @throws AwesomeException
   */
  public boolean uploadFile(InputStream in, String targetDir, String targetFileName, SftpProgressMonitor monitor) throws AwesomeException {
    ChannelSftp channelSftp = null;
    try {
      channelSftp = this.objectPool.borrowObject();
      // 如果不存在目标文件夹
      if (!exist(channelSftp, targetDir)) {
        mkdirs(channelSftp, targetDir);
      }
      channelSftp.cd(targetDir);
      if (Objects.nonNull(monitor)) {
        channelSftp.put(in, targetFileName, monitor);
      } else {
        channelSftp.put(in, targetFileName);
      }
      return true;
    } catch (Exception e) {
      throw new AwesomeException(500, "upload file fail");
    } finally {
      if (Objects.nonNull(channelSftp)) {
        this.objectPool.returnObject(channelSftp);
      }
    }
  }
  /**
   * 下载文件
   *
   * @param remoteFile
   * @param targetFilePath
   * @return
   * @throws AwesomeException
   */
  public boolean downloadFile(String remoteFile, String targetFilePath) throws AwesomeException {
    return downloadFile(remoteFile, targetFilePath, null);
  }
  /**
   * 下载目标文件到本地
   *
   * @param remoteFile
   * @param targetFilePath
   * @return
   * @throws AwesomeException
   */
  public boolean downloadFile(String remoteFile, String targetFilePath, SftpProgressMonitor monitor) throws AwesomeException {
    ChannelSftp channelSftp = null;
    try {
      channelSftp = this.objectPool.borrowObject();
      // 如果不存在目标文件夹
      if (!exist(channelSftp, remoteFile)) {
        // 不用下载了
        return false;
      }
      File targetFile = new File(targetFilePath);
      try (FileOutputStream outputStream = new FileOutputStream(targetFile)) {
        if (Objects.nonNull(monitor)) {
          channelSftp.get(remoteFile, outputStream, monitor);
        } else {
          channelSftp.get(remoteFile, outputStream);
        }
      }
      return true;
    } catch (Exception e) {
      throw new AwesomeException(500, "upload file fail");
    } finally {
      if (Objects.nonNull(channelSftp)) {
        this.objectPool.returnObject(channelSftp);
      }
    }
  }
  /**
   * 下载文件
   *
   * @param remoteFile
   * @param outputStream
   * @return
   * @throws AwesomeException
   */
  public boolean downloadFile(String remoteFile, OutputStream outputStream) throws AwesomeException {
    return downloadFile(remoteFile, outputStream, null);
  }
  /**
   * 下载文件
   *
   * @param remoteFile
   * @param outputStream
   * @param monitor
   * @return
   * @throws AwesomeException
   */
  public boolean downloadFile(String remoteFile, OutputStream outputStream, SftpProgressMonitor monitor) throws AwesomeException {
    ChannelSftp channelSftp = null;
    try {
      channelSftp = this.objectPool.borrowObject();
      // 如果不存在目标文件夹
      if (!exist(channelSftp, remoteFile)) {
        // 不用下载了
        return false;
      }
      if (Objects.nonNull(monitor)) {
        channelSftp.get(remoteFile, outputStream, monitor);
      } else {
        channelSftp.get(remoteFile, outputStream);
      }
      return true;
    } catch (Exception e) {
      throw new AwesomeException(500, "upload file fail");
    } finally {
      if (Objects.nonNull(channelSftp)) {
        this.objectPool.returnObject(channelSftp);
      }
    }
  }
  /**
   * 创建文件夹
   *
   * @param channelSftp
   * @param dir
   * @return
   */
  protected boolean mkdirs(ChannelSftp channelSftp, String dir) {
    try {
      String pwd = channelSftp.pwd();
      if (StringUtils.contains(pwd, dir)) {
        return true;
      }
      String relativePath = StringUtils.substringAfter(dir, pwd);
      String[] dirs = StringUtils.splitByWholeSeparatorPreserveAllTokens(relativePath, "/");
      for (String path : dirs) {
        if (StringUtils.isBlank(path)) {
          continue;
        }
        try {
          channelSftp.cd(path);
        } catch (SftpException e) {
          channelSftp.mkdir(path);
          channelSftp.cd(path);
        }
      }
      return true;
    } catch (Exception e) {
      return false;
    }
  }
  /**
   * 判断文件夹是否存在
   *
   * @param channelSftp
   * @param dir
   * @return
   */
  protected boolean exist(ChannelSftp channelSftp, String dir) {
    try {
      channelSftp.lstat(dir);
      return true;
    } catch (Exception e) {
      return false;
    }
  }

Integrate into SpringBoot In

we can use java config to instantiate the SftpClient class we have implemented into the Spring IOC container for management , so that developers can use it directly throughout the entire project through @Autowired.

Configuration

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
/**
 * @author zouwei
 * @className SftpProperties
 * @date: 2022/8/19 下午12:12
 * @description:
 */
@Data
@Configuration
@ConfigurationProperties(prefix = "sftp.config")
public class SftpProperties {
  // 用户名
  private String username;
  // 密码
  private String password;
  // 主机名
  private String host;
  // 端口
  private int port;
  // 密钥
  private String privateKeyFile;
  // 口令
  private String passphrase;
  // 通道链接超时时间
  private int timeout;
  // 链接池配置
  private PoolConfig pool;
  @Data
  public static class PoolConfig {
    //最大空闲实例数,空闲超过此值将会被销毁淘汰
    private int maxIdle;
    // 最小空闲实例数,对象池将至少保留2个空闲对象
    private int minIdle;
    //最大对象数量,包含借出去的和空闲的
    private int maxTotal;
    //对象池满了,是否阻塞获取(false则借不到直接抛异常)
    private boolean blockWhenExhausted;
    // BlockWhenExhausted为true时生效,对象池满了阻塞获取超时,不设置则阻塞获取不超时,也可在borrowObject方法传递第二个参数指定本次的超时时间
    private long maxWaitMillis;
    // 创建对象后是否验证对象,调用objectFactory#validateObject
    private boolean testOnCreate;
    // 借用对象后是否验证对象 validateObject
    private boolean testOnBorrow;
    // 归还对象后是否验证对象 validateObject
    private boolean testOnReturn;
    // 定时检查期间是否验证对象 validateObject
    private boolean testWhileIdle;
    //定时检查淘汰多余的对象, 启用单独的线程处理
    private long timeBetweenEvictionRunsMillis;
    //jmx监控,和springboot自带的jmx冲突,可以选择关闭此配置或关闭springboot的jmx配置
    private boolean jmxEnabled;
  }
}

java Bean Injection

import com.example.awesomespring.exception.AwesomeException;
import com.example.awesomespring.sftp.SftpClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
 * @author zouwei
 * @className SftpConfig
 * @date: 2022/8/19 下午12:12
 * @description:
 */
@Configuration
public class SftpConfig {
  @Autowired
  private SftpProperties properties;
  // 创建SftpClient对象
  @Bean(destroyMethod = "close")
  @ConditionalOnProperty(prefix = "sftp.config")
  public SftpClient sftpClient() throws AwesomeException {
    return new SftpClient(properties);
  }
}

With the above code, we can directly use the SFTP client to upload and download files anywhere in the project.

The above is the detailed content of How does SpringBoot integrate SFTP client to upload and download files?. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
怎么使用SpringBoot+Canal实现数据库实时监控怎么使用SpringBoot+Canal实现数据库实时监控May 10, 2023 pm 06:25 PM

Canal工作原理Canal模拟MySQLslave的交互协议,伪装自己为MySQLslave,向MySQLmaster发送dump协议MySQLmaster收到dump请求,开始推送binarylog给slave(也就是Canal)Canal解析binarylog对象(原始为byte流)MySQL打开binlog模式在MySQL配置文件my.cnf设置如下信息:[mysqld]#打开binloglog-bin=mysql-bin#选择ROW(行)模式binlog-format=ROW#配置My

Spring Boot怎么使用SSE方式向前端推送数据Spring Boot怎么使用SSE方式向前端推送数据May 10, 2023 pm 05:31 PM

前言SSE简单的来说就是服务器主动向前端推送数据的一种技术,它是单向的,也就是说前端是不能向服务器发送数据的。SSE适用于消息推送,监控等只需要服务器推送数据的场景中,下面是使用SpringBoot来实现一个简单的模拟向前端推动进度数据,前端页面接受后展示进度条。服务端在SpringBoot中使用时需要注意,最好使用SpringWeb提供的SseEmitter这个类来进行操作,我在刚开始时使用网上说的将Content-Type设置为text-stream这种方式发现每次前端每次都会重新创建接。最

SpringBoot怎么实现二维码扫码登录SpringBoot怎么实现二维码扫码登录May 10, 2023 pm 08:25 PM

一、手机扫二维码登录的原理二维码扫码登录是一种基于OAuth3.0协议的授权登录方式。在这种方式下,应用程序不需要获取用户的用户名和密码,只需要获取用户的授权即可。二维码扫码登录主要有以下几个步骤:应用程序生成一个二维码,并将该二维码展示给用户。用户使用扫码工具扫描该二维码,并在授权页面中授权。用户授权后,应用程序会获取一个授权码。应用程序使用该授权码向授权服务器请求访问令牌。授权服务器返回一个访问令牌给应用程序。应用程序使用该访问令牌访问资源服务器。通过以上步骤,二维码扫码登录可以实现用户的快

SpringBoot/Spring AOP默认动态代理方式是什么SpringBoot/Spring AOP默认动态代理方式是什么May 10, 2023 pm 03:52 PM

1.springboot2.x及以上版本在SpringBoot2.xAOP中会默认使用Cglib来实现,但是Spring5中默认还是使用jdk动态代理。SpringAOP默认使用JDK动态代理,如果对象没有实现接口,则使用CGLIB代理。当然,也可以强制使用CGLIB代理。在SpringBoot中,通过AopAutoConfiguration来自动装配AOP.2.Springboot1.xSpringboot1.xAOP默认还是使用JDK动态代理的3.SpringBoot2.x为何默认使用Cgl

spring boot怎么对敏感信息进行加解密spring boot怎么对敏感信息进行加解密May 10, 2023 pm 02:46 PM

我们使用jasypt最新版本对敏感信息进行加解密。1.在项目pom文件中加入如下依赖:com.github.ulisesbocchiojasypt-spring-boot-starter3.0.32.创建加解密公用类:packagecom.myproject.common.utils;importorg.jasypt.encryption.pbe.PooledPBEStringEncryptor;importorg.jasypt.encryption.pbe.config.SimpleStrin

使用Java SpringBoot集成POI实现Word文档导出使用Java SpringBoot集成POI实现Word文档导出Apr 21, 2023 pm 12:19 PM

知识准备需要理解ApachePOI遵循的标准(OfficeOpenXML(OOXML)标准和微软的OLE2复合文档格式(OLE2)),这将对应着API的依赖包。什么是POIApachePOI是用Java编写的免费开源的跨平台的JavaAPI,ApachePOI提供API给Java程序对MicrosoftOffice格式档案读和写的功能。POI为“PoorObfuscationImplementation”的首字母缩写,意为“简洁版的模糊实现”。ApachePOI是创建和维护操作各种符合Offic

springboot怎么整合shiro实现多验证登录功能springboot怎么整合shiro实现多验证登录功能May 10, 2023 pm 04:19 PM

1.首先新建一个shiroConfigshiro的配置类,代码如下:@ConfigurationpublicclassSpringShiroConfig{/***@paramrealms这儿使用接口集合是为了实现多验证登录时使用的*@return*/@BeanpublicSecurityManagersecurityManager(Collectionrealms){DefaultWebSecurityManagersManager=newDefaultWebSecurityManager();

Springboot如何实现视频上传及压缩功能Springboot如何实现视频上传及压缩功能May 10, 2023 pm 05:16 PM

一、定义视频上传请求接口publicAjaxResultvideoUploadFile(MultipartFilefile){try{if(null==file||file.isEmpty()){returnAjaxResult.error("文件为空");}StringossFilePrefix=StringUtils.genUUID();StringfileName=ossFilePrefix+"-"+file.getOriginalFilename(

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft