簡體   English   中英

使用Ajax將數據發布到Java Servlet

[英]Post data with ajax to java servlet

首先,如果我的英語不好,請原諒我。 使用ajax將數據發送到我的ExportServlet時遇到一些問題。

ExportServlet.java

public class ExportServlet extends HttpServlet {
private static final long serialVersionUID = 6715605810229670146L;

protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    String fileName = req.getParameter("filename");

    //Create ZIP file
    try {
        res.setContentType("applicatin/zip");
        res.setStatus(HttpServletResponse.SC_OK);

        ZipOutputStream zos = new ZipOutputStream(res.getOutputStream());

        //Create TXT file
        zos.putNextEntry(new ZipEntry(fileName + ".txt"));
        zos.write(getOutputData());
        zos.closeEntry();

        zos.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

private byte[] getOutputData() {
    byte[] result = null;
    String tmp = "Text file content";
    result = tmp.getBytes();
    return result;
}
}

上面的Java代碼絕對完美。

然后,我有了將數據發送到ExportServlet的ajax代碼(我以文件名為例):

//Post data to ExportServlet
        $.ajax({
            type: 'post',
            url: '/export.zip',
            data: "filename = myFile",
            success:function(data){alert(data);},
            error:function(){alert('error');}
        });

問題是當ajax函數被觸發時,我得到一個錯誤回調。 我還有一個鏈接可以下載ExportServlet生成的ZIP文件:

<a href="/export.zip">Download file</a>

確實,當我單擊鏈接時,我得到的ZIP文件中帶有“ null.txt”。 我怎樣才能解決這個問題?

在此先多謝!

嘗試這個:

<a href="javascript:;" onclick="downloadFile();">Download file</a>
<div style="display: none;">
   <iframe id="downloadFileFrame"></iframe>
</div>


function downloadFile() {
    $('#downloadFileFrame').attr('src','/export.zip?filename=myFile');
    return false;
}

當您單擊鏈接時,不會調用ajax代碼,因此filename參數不會包含在對servlet的請求中。 servlet將以filename = null的方式執行。 那就是你得到的實際結果。

為了解決這個問題,我認為您必須在頁面首次加載時調用ajax代碼,以便servlet可以創建文件並將其放置在服務器上。 然后,您必須在鏈接中傳遞filename參數,例如:

<a href="http://yourdomain.com/downloadFile?filename=myFile">Download file</a>

downloadFile servlet將查找名為myFile.txt的文件,該文件是在您的頁面首次加載名為ajax的文件時創建的,並提供了相應的文件。

暫無
暫無

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

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