Skip to content Skip to sidebar Skip to footer

How To Stream Text Response To Jsp From Servlet?

I have a long running servlet process that is being called from a JSP. I would like to send the status of the servlet process to the client as it is happening. I have everything wo

Solution 1:

There was one big issue and a few small issues with the original code posted in this question. The big issue was this line: resp.setContentType("text/plain");. Changing this line to resp.setContentType("application/text"); fixed the streaming issue on the server side. More substantial changes were made to the client code. The code below works and is a complete working solution for posting a multipart form to a server and getting a streaming response from the server as it occurs (several values are hard coded and need to be cleaned up but it gets the job done).

Sever Code:

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    log.info("----------");
    log.info("Doing post");
    resp.setContentType("application/text");
    OutputStream out = resp.getOutputStream();
    out.write("Writing file to server".getBytes());
    out.flush();
    writeZipFileToDisc(req, resp);
    out.write("\n\nDone.\n".getBytes());
    out.flush();
    log.info("Done.");
}

Client Code:

postUploadFile = function() {
    $("#status").val("");
    YES.getAndShowStatus("status", "${home}/Upload");
}

YES.getAndShowStatus = function(listenerId, url, successFunction) {
    // based on https://gist.github.com/sohelrana820/63f029d3aa12936afbc50eb785c496c0
    var form = $("#uploadForm")[0];
    var data = new FormData(form);
    $.ajax({
        type: "POST",
        enctype: 'multipart/form-data',
        url: url,
        data: data,
        processData: false,
        contentType: false,
        cache: false,
        xhrFields: {
            // Getting on progress streaming response
            onprogress: function(e)
            {
                var progressResponse;
                var response = e.currentTarget.response;
                val = jQuery("#" + listenerId).val();
                jQuery("#" + listenerId).val(response);

            }
        }
    });

};

Post a Comment for "How To Stream Text Response To Jsp From Servlet?"