简体   繁体   English

上传文件后 Servlet 中的 response.sendRedirect() 无法正常工作

[英]response.sendRedirect() in Servlet not working correctly after file upload

I have a web application with a simple upload function.我有一个 web 应用程序,只需简单上传 function。 The idea is to allow user select a file and upon successfully upload, redirect to index.jsp .这个想法是允许用户 select 一个文件,并在成功上传后重定向到index.jsp

However, although the file got uploaded, the response.redirect is not working.但是,尽管文件已上传,但response.redirect不起作用。 After a successfully upload, the page doesn't get redirected.成功上传后,页面不会被重定向。 It just stays there.它只是停留在那里。 The weird thing is that I can see it is processing the index.jsp from the tomcat server log even though it doesn;t get redirected.奇怪的是,我可以看到它正在处理来自 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();
    }

}

The redirect method:重定向方法:

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

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

The file upload plugin is from https://aquantum-demo.appspot.com/file-upload I used the front-end and developed the upload event handler using java apache fileupload.文件上传插件来自https://aquantum-demo.appspot.com/file-upload我使用前端并使用 java ZB6EFD606D118D0F62066E3CCZ9 文件开发上传事件处理程序。 Everything works fine except the redirect part.除重定向部分外,一切正常。

The application.js file which handles the JSON returns:处理 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();
    });
});

}); });

Any ideas?有任何想法吗?

You're attempting to send two responses on a single request.您试图在一个请求上发送两个响应。 One with JSON data in the response body and one which redirects the response to another request.一个在响应正文中包含 JSON 数据,另一个将响应重定向到另一个请求。 This is not going to work.这是行不通的。 You can send only one response back per request.每个请求只能发回一个响应。 A redirect requires an untouched (uncommitted) response body, otherwise the redirect will just fail with IllegalStateException: response already committed in the server logs.重定向需要一个未触及(未提交)的响应主体,否则重定向将失败,并显示IllegalStateException: response already committed

You need to move the redirect call from the servlet code to JavaScript code.您需要将重定向调用从 servlet 代码移动到 JavaScript 代码。 Get rid of the redirect() line in the servlet and add the following line as the last line of the $.getJSON() callback function.去掉 servlet 中的redirect()行,添加以下行作为$.getJSON()回调 function 的最后一行。

window.location = '/index.jsp';

This way JavaScript will take care of the redirect.这样 JavaScript 将负责重定向。

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

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