Search code examples
jsphttp-redirectservletsdownload

How to send a redirect after generating a file download in Servlet


I'm developing a web page using Java Servlets and JSP. I have functionality where, depending on the received action (action), different operations are performed. However, I'm encountering an issue with a specific action (action4) which should generate a PDF and then redirect the user to another page.

Questions:

  • How can I correctly redirect to a page after generating the PDF?
  • Is there a way to complete the PDF download and then perform the redirection?

I appreciate any help or suggestions you can offer. Thanks in advance!

Below is my structure and the problem I'm facing.

Servlet:

if (action != null) {
    switch (action) {
        case "action1": // Add items to cart
            if (carritoSQL.existeProducto(producto)) {
                handleAddButton(request, response, producto, cantidad, carrito);
            }
            break;
        case "action2": // Development-focused case
            handleClearButton(request, response, session);
            break;
        case "action3": // Cancel purchase
            handleClearButton(request, response, session);
            redirect = "views/home.jsp";
            break;
        case "action4": // Complete purchase
            handleCompletePurchaseButton(request, response, fecha, vendedor, distribuidor, carrito);
            handleClearButton(request, response, session);
            request.getRequestDispatcher("views/home.jsp").forward(request, response);
            //redirect = "views/home.jsp";
            break;
        default:
            // Default logic if necessary
            defaultHandler(request, response);
            redirect = "views/home.jsp";
            break;
    }
} else {
    // Handle the case where no 'action' value is received
    defaultHandler(request, response);
}

response.sendRedirect(redirect);

private void handleCompletePurchaseButton(HttpServletRequest request, HttpServletResponse response, String fecha, String vendedor, String distribuidor, ShoppingCart carrito) throws ServletException, IOException {
    GeneralReceipt receipt = createReceipt(fecha, vendedor, distribuidor, carrito);
    detailReceipt(receipt.getId(), fecha, vendedor, distribuidor, carrito);
    String ticket = generateTicketString(vendedor, distribuidor, carrito, receipt);
    generatePDF(response, ticket, distribuidor, fecha);
}

Problem: The issue occurs with action4. The operation correctly generates the PDF, which is then downloaded by the user, but the redirection to the page does not occur. I tried the following solutions:

  • response.sendRedirect("views/home.jsp");
  • request.getRequestDispatcher("views/home.jsp").forward(request, response);

Both solutions result in the following error in the console:

28-Jun-2024 10:50:29.355 SEVERE [68] org.apache.catalina.core.StandardWrapperValve.invoke Servlet.service() for servlet [operacionesRemisionNH1] threw exception
    java.lang.IllegalStateException: Cannot call sendRedirect() after the response has been committed
        at org.apache.catalina.connector.ResponseFacade.sendRedirect(ResponseFacade.java:486)
        at Servlets.operacionesRemisionNH1.generatePDF(operacionesRemisionNH1.java:354)
        at Servlets.operacionesRemisionNH1.handleCompletePurchaseButton(operacionesRemisionNH1.java:153)
        at Servlets.operacionesRemisionNH1.doPost(operacionesRemisionNH1.java:114)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:681)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:764)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:232)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:167)

JSP where I call action4:

<div class="modal fade" id="FinalizarCompraModal" tabindex="-1" aria-labelledby="FinalizarCompraModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="FinalizarCompraModalLabel">Purchase Confirmation</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                You are about to complete your purchase. Please review your order details. If everything is correct, click 'Confirm' to complete the purchase. If you need to make any changes, click 'Cancel'.
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="submit" name="action" value="action4" class="btn btn-primary">Confirm</button>
            </div>
        </div>
    </div>
</div>


Solution

  • Indeed, you can't send multiple responses back for a single request. You basically need to trigger a second request afterwards.

    Your best bet is to add a specific cookie to the response representing the file download and poll for it in JavaScript and then perform a redirect in JavaScript when the cookie is found.

    Basically, in Servlet:

    response.setHeader("Content-Disposition", ...);
    response.addCookie(new Cookie("download.completed", "true"));
    // now write to response.getOutputStream()
    

    And in JSP, give the download button an ID so we can reference it in JS:

    <button type="submit" id="yourDownloadButton" ...>
    

    And run this JS when DOM content is ready so that the cookie poller is launched when the download button is clicked. When the cookie is found then this example will show an alert (for demo purposes of course, you can safely remove it) and then redirect to your current question:

    document.getElementById("yourDownloadButton").addEventListener("click", () => {
        document.cookie = "download.completed=false";
        const downloadCompleteChecker = setInterval(() => {
            if (document.cookie.includes("download.completed=true")) {
                clearInterval(downloadCompleteChecker);
                alert("Download completed!");
                window.location = "https://stackoverflow.com/q/78683578";
            }
        }, 500);
    });