簡體   English   中英

在.jsp文件中顯示.java的輸出

[英]display output from .java in .jsp file

我有一個Java文件,該文件正在連接到ftp服務器並從服務器帶回目錄列表。 我的問題是從java文件中獲取列表並在jsp中顯示目錄結果的正確方法是什么?

您是否建議我直接從jsp連接到ftp服務器,或者這是不良的編碼做法?

例:

連接.java

package root;
import java.io.IOException;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;


public class ConnectFTP {


private void showServerReply(FTPClient ftpClient) {
    String[] replies = ftpClient.getReplyStrings();
    if (replies != null && replies.length > 0) {
        for (String aReply : replies) {
            System.out.println("SERVER: " + aReply);
        }
    }
}



public void listFTPVendors(String[] args) {
    String server = "ftpserver.com";
    int port = 21;
    String user = "username";
    String pass = "password";
    FTPClient ftpClient = new FTPClient();
    try {
        ftpClient.connect(server, port);
        showServerReply(ftpClient);
        int replyCode = ftpClient.getReplyCode();C
        if (!FTPReply.isPositiveCompletion(replyCode)) {
            System.out.println("Operation failed. Server reply code: " + replyCode);
            return;
        }
        boolean success = ftpClient.login(user, pass);
        showServerReply(ftpClient);
        if (!success) {
            System.out.println("Could not login to the server");
            return;
        } else {
            System.out.println("LOGGED IN SERVER");
        }
        FTPFile[] files = ftpClient.listDirectories();
        for (FTPFile file : files) {
            String details = file.getName();
            if (file.isDirectory()) {
                details = "[" + details + "]";
            }
            System.out.println(details);
        }

    } catch (IOException ex) {
        System.out.println("Oops! Something wrong happened");
        ex.printStackTrace();
    }


}

}

Connect.jsp

??

我只是在尋找建議,不一定是代碼。 甚至一些閱讀材料。 相當新的和丟失的...

return files而不是遍歷files並進行打印,而是return files並將listFTPVendors(String[] args)方法的返回類型更改為FTPFile[]

現在,從您的JSP調用此方法並以JSP代碼檢索數據。

<%FTPFile[] files = new ConnectFTP().listFTPVendors()%>

不要忘記在JSP導入ConnectFTP類。

遍歷JSP files並將其顯示在網頁上。

是的,JSP用於表示邏輯,因此如果將網絡代碼保存在單獨的Java文件中會更好:)

我看到您正在使用Apache Commons FTP API。 您幾乎可以正確執行此操作。

我還相信,當您的集合僅由目錄組成時,您不必要測試目錄。 這是因為您正在使用listDirectories()方法。
如果您調用listFiles(),則必須像已經完成的那樣測試每個文件是一個目錄。

您應該能夠如下修改代碼:

...
FTPFile[] files = ftpClient.listDirectories();
for (FTPFile file : files) {
    System.out.println("["+ file.getName() +"]");
}
...

至於直接從您的JSP頁面連接到FTP服務器-那里沒有任何“錯誤”,但是通常jsp用於顯示目的。

我將避免對頁面中的憑據進行硬編碼-應該將它們外部化為配置文件。 配置文件也應存儲在無法通過瀏覽器訪問的位置。

根據您使用的Web框架-您可能希望將此功能包裝到控制器或服務中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM