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>

New contributor

Carlos Odette DLCL is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

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 = "/q/78683578";
        }
    }, 500);
});

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật