首页 > 解决方案 > 如何将 FTP 从 Spring MVC 转换为 Spring Boot/Thymeleaf?

问题描述

所以我一直在努力从一个旧的 webapp 中获取逻辑,并从中制作一个新的 Spring Boot 应用程序。我遇到了关于 ftp 连接和呼叫的问题。由于我没有这方面的经验,我很好奇是否有更好/更现代的方法来使用 Spring Boot/Thymeleaf 处理大部分 ftp 内容以及继续进行设置的方法。任何建议/指导都会很棒。

这是我想稍微现代化的旧代码。

String serverName = getFtpServer();

// Connect to the server
try {
    ftp.connect(serverName);
    ftp.enterLocalPassiveMode();
    String replyText = ftp.getReplyString();
    System.out.println(replyText);
} catch (Exception e) {
    e.printStackTrace();
    return false;
}

// Login to the server
try {
    ftp.login(userName, password);
    String replyText = ftp.getReplyString();
    System.out.println(replyText);
} catch (Exception e) {
    e.printStackTrace();
    return false;
}

// Tell server that the file will have JCL records
try {
    ftp.site("filetype=jes");
    String replyText = ftp.getReplyString();
    System.out.println(replyText);
} catch (Exception e) {
    e.printStackTrace();
    return false;
}

// Submit and run the JCL
try {
    System.out.println("TRYING TO START MAINFRAME JCL");
    submitJcl(filename, serverName);

    String replyText = ftp.getReplyString();
    System.out.println(replyText);
} catch (Exception e) {
    String replyText = ftp.getReplyString();
    System.out.println(replyText);
    e.printStackTrace();
    return false;
}

// Quit the server
try {
    ftp.quit();
} catch (Exception e) {
    e.printStackTrace();
}

存储文件

private String submitJcl(String remoteFile, String serverName) throws IOException {
    String filePath = getFilePath();
    String result = "";
    String fileName = filePath + remoteFile;
    System.out.println("filePath = " + fileName);
    FileInputStream inputStream = new FileInputStream(fileName);
    ftp.storeFile(serverName, inputStream);

    return result;
}

标签: javaspring-bootftpthymeleaf

解决方案


为此,我发现可能有更好的方法将其更改为 Spring Boot 的更新 ftp 格式,但这仍然完全有效。

不管怎样,我对它所做的更改:

  • 将 try/catch 块合并为一个。
  • 将 ftp 内容推送到它自己的函数中,然后在 try/catch 块中调用它
  • 将所有 sys.out 更改为 info.debugs。
  • 将获取 filePath 的方式更改为与存储在系统中的文件而不是用户文件的相对路径。

推荐阅读