简体   繁体   English

使用Ajax将数据发布到Java Servlet

[英]Post data with ajax to java servlet

First of all, pardon me if my english is bad. 首先,如果我的英语不好,请原谅我。 I'm having some problems with sending data to my ExportServlet with ajax. 使用ajax将数据发送到我的ExportServlet时遇到一些问题。

ExportServlet.java 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;
}
}

The java code above works absolutely perfect. 上面的Java代码绝对完美。

Then I have my ajax code that sends data to my ExportServlet (I have used filename for an example): 然后,我有了将数据发送到ExportServlet的ajax代码(我以文件名为例):

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

The problem is that when the ajax function is triggered I get an error callback. 问题是当ajax函数被触发时,我得到一个错误回调。 I also have a link to download the ZIP file generated by ExportServlet: 我还有一个链接可以下载ExportServlet生成的ZIP文件:

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

And indeed, when I click the link I get ZIP file with "null.txt" in it. 确实,当我单击链接时,我得到的ZIP文件中带有“ null.txt”。 How can I fix this? 我怎样才能解决这个问题?

Thanks alot in advance! 在此先多谢!

Try this: 尝试这个:

<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;
}

When you click on the link, the ajax code will not be called so the filename parameter will not be included in the request to the servlet. 当您单击链接时,不会调用ajax代码,因此filename参数不会包含在对servlet的请求中。 The servlet will execute with filename = null. servlet将以filename = null的方式执行。 That is the actual result you got. 那就是你得到的实际结果。

To fix this, I think you have to call the ajax code at the first time the page loaded so that your servlet can create a file and place it on the server. 为了解决这个问题,我认为您必须在页面首次加载时调用ajax代码,以便servlet可以创建文件并将其放置在服务器上。 Then you have to pass filename parameter in your link such as: 然后,您必须在链接中传递filename参数,例如:

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

The downloadFile servlet will look for file named myFile.txt which was created at the first time your page loaded with ajax called, and give you the file in response. downloadFile servlet将查找名为myFile.txt的文件,该文件是在您的页面首次加载名为ajax的文件时创建的,并提供了相应的文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM