【问题标题】:response.sendRedirect() in Servlet not working correctly after file upload上传文件后 Servlet 中的 response.sendRedirect() 无法正常工作
【发布时间】:2011-09-28 06:40:12
【问题描述】:

我有一个带有简单上传功能的网络应用程序。这个想法是允许用户选择一个文件并在成功上传后重定向到index.jsp

但是,虽然文件已上传,但 response.redirect 无法正常工作。成功上传后,页面不会被重定向。它只是停留在那里。奇怪的是,我可以看到它正在处理来自 tomcat 服务器日志的index.jsp,即使它没有被重定向。

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    //processRequest(request, response);
    boolean status=false;
    if (!ServletFileUpload.isMultipartContent(request)) {
        throw new IllegalArgumentException("Request is not multipart, please 'multipart/form-data' enctype for your form.");
    }

    ServletFileUpload uploadHandler = new ServletFileUpload(new DiskFileItemFactory());
    PrintWriter writer = response.getWriter();
    response.setContentType("text/plain");
    try {

        List<FileItem> items = uploadHandler.parseRequest(request);
        for (FileItem item : items) {
            if (!item.isFormField()) {
                File file = new File(getServletContext().getRealPath("/WEB-INF/upload"), item.getName());
                item.write(file);
                writer.write("{\"name\":\"" + item.getName() + "\",\"type\":\"" + item.getContentType() + "\",\"size\":\"" + item.getSize() + "\"}");

            }

        }

        //redirect to index.jsp if successfully

        redirect(request, response);

    } catch (FileUploadException e) {
        throw new RuntimeException(e);
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
      writer.close();
    }

}

重定向方法:

private void redirect(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    request.getRequestDispatcher("/index.jsp").forward(request, response);
}

文件上传插件来自https://aquantum-demo.appspot.com/file-upload 我使用前端并使用 java apache fileupload 开发了上传事件处理程序。除了重定向部分,一切正常。

处理 JSON 返回的 application.js 文件:

$(function () {
// Initialize jQuery File Upload (Extended User Interface Version):
$('#file_upload').fileUploadUIX();

// Load existing files:
$.getJSON($('#file_upload').fileUploadUIX('option', 'url'), function (files) {
    var options = $('#file_upload').fileUploadUIX('option');
    options.adjustMaxNumberOfFiles(-files.length);
    $.each(files, function (index, file) {
        options.buildDownloadRow(file, options)
            .appendTo(options.downloadTable).fadeIn();
    });
});

});

有什么想法吗?

【问题讨论】:

  • 代码看起来不错。但是,如果您在 try 之前取消注释两个输出之一,那么重定向确实可能会失败(在服务器日志中带有 IllegalStateException)。你真的在运行你认为你正在运行的代码吗?
  • 我已经设法找出问题所在。是的,你是对的,上传处理程序工作正常。问题在于正在运行的前端 js 脚本。每次成功上传后,都需要返回一个 JSON 响应,这会导致之后附加的任何代码都失败。我已经编辑了上面的代码来显示问题。有什么解决办法吗?

标签: java javascript jquery servlets file-upload


【解决方案1】:

您正尝试在一个请求中发送两个响应。一个在响应正文中包含 JSON 数据,另一个将响应重定向到另一个请求。这是行不通的。对于每个请求,您只能返回一个响应。重定向需要一个未触及(未提交)的响应正文,否则重定向将失败,并在服务器日志中显示 IllegalStateException: response already committed

您需要将重定向调用从 servlet 代码移动到 JavaScript 代码。去掉servlet中的redirect()这一行,在$.getJSON()回调函数的最后一行加入下面一行。

window.location = '/index.jsp';

这样 JavaScript 将负责重定向。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多