Solved

How to forwrd to another server/jsp page when file downloading finished in one servlet page.

Posted on 2004-10-28
350 Views
Last Modified: 2010-04-01
I have a file download servlet that allow user to download a file from ftp.
when download finished, i need to forwared to other page (jsp or servlet). but when i do it, error :

IllegalStateException : 'Cannot forward after response has been committed '

=============source code =========================
package downloadservlet;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import java.net.URL;
import java.net.MalformedURLException;

/**
 * <p>Title: </p>
 * <p>Description: </p>
 * <p>Copyright: Copyright (c) 2004</p>
 * <p>Company: </p>
 * @author not attributable
 * @version 1.0
 */

public class downloadServlet extends HttpServlet {
  private static final String CONTENT_TYPE = "text/html; charset=GBK";
  //Initialize global variables
  public void init() throws ServletException {
  }
  //Process the HTTP Get request
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//    response.setContentType(CONTENT_TYPE);
//    PrintWriter out = response.getWriter();
//    out.println("<html>");
//    out.println("<head><title>downloadServlet</title></head>");
//    out.println("<body bgcolor=\"#ffffff\">");
//    out.println("<p>The servlet has received a " + request.getMethod() + ". This is the reply.</p>");
//    out.println("</body></html>");
    OutputStream out=response.getOutputStream();
    response.setContentType("application/download");
    response.setHeader("Content-Disposition",
                       "attachment; filename=example.pdf");
    String fileURL="ftp://172.21.240.48/etd-0730102-141304.pdf";
    BufferedInputStream bis = null;
    BufferedOutputStream bos = null;
    try {
      URL url = new URL(fileURL);


      bis = new BufferedInputStream(url.openStream());
      bos = new BufferedOutputStream(out);

      byte[] buff = new byte[2048];
      int bytesRead;

      while ( -1 != (bytesRead = bis.read(buff, 0, buff.length))) {
        bos.write(buff, 0, bytesRead);
      }

      System.out.println("Download completed");
     
      ///////ERROR OCCURED/////////////
      (request.getRequestDispatcher("aaa.jsp")).forward(request,response);   ///
    }
    catch (final MalformedURLException e) {
      throw e;
    }
    catch (final IOException e){
      throw e;
    }
    finally {
      if (bis != null)
      {
        bis.close();
      }
      if( bos != null)
      {
        bos.close();
      }
    }

  }
  //Process the HTTP Post request
  public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    doGet(request, response);
  }
  //Clean up resources
  public void destroy() {
  }
}


Is there have any way i can forware to other page after download completed ?
0
Question by:wizlokesh
    10 Comments
     
    LVL 35

    Accepted Solution

    by:
    Not with doing it this way...  the problem is that you cannot send a forward or a redirect AFTER you have sent some data...  

    That's not part of the HTML spec, so can't be done :-(

    Hmmmm...  

    Does this work:

        RequestDispatcher disp;
        disp = request.getRequestDispatcher( "aaa.jsp" ) ;
        disp.include( request, response ) ;

    it might do (it is basically a server side include),

    But it might not :-/

    Good luck

    Tim
    0
     
    LVL 13

    Assisted Solution

    by:petmagdy
    Yes this is known and normal, on the response u can't change any attribute of the response and then forward,

    I see u forward to the aaa jsp after doing set content type, header and sending contents

    I think the line:

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

    mean't to be in somewhere else
    0
     
    LVL 13

    Expert Comment

    by:petmagdy
    If u want to forward to JSP after finishing download use sendRedirect
    0
     
    LVL 35

    Expert Comment

    by:TimYates
    >  If u want to forward to JSP after finishing download use sendRedirect

    But sendRedirect doesn't work after a response has been started or committed either...

    So that would give the same error...
    0
     
    LVL 35

    Expert Comment

    by:TimYates
    From the API docs for "HttpServletResponse.sendRedirect()":

    ---------

        If the response has already been committed, this method throws an IllegalStateException. After using this method, the response should be considered to be committed and should not be written to.
    0
     
    LVL 13

    Expert Comment

    by:petmagdy
    right TimYates,

    Anyway i never saw a web application forwards a user to a page after downloading something, it is usually the opposite
    0
     
    LVL 35

    Expert Comment

    by:TimYates
    True...  Usually you are left on the download page (as it makes it easier to re-start the download if it stops, or has errors)

    I wonder if the "include" method works though...  

    All of my gut tells me no...  

    But a small part of my brain says "maybe" in a very quiet voice

    ;-)
    0
     
    LVL 2

    Expert Comment

    by:siliconeagle
    you can use javascript:-
    first link to your JSP page you want to forward to.
    add some code in your jsp page as such:-
    <script language="javascript">
    function downloadPDF() {
       document.location.href="<path to servlet>";
    }
    <script>
    <body  onload="downloadPDF();">
    get rid of the forward in your servlet
    i usually set response.setContentType("application/octet-stream"); , not "application/download" but it might work as well.

    this will have the effect you're looking for, i think. The pdf will download and ask the user to save without giong to another page.
    0
     
    LVL 35

    Expert Comment

    by:TimYates
    I think the idea is to go to a different page once the download is complete...
    0
     
    LVL 35

    Expert Comment

    by:TimYates
    The answer to this question is "you can't"

    so I reckon a split between TimYates and petmagdy
    0

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    Anonabox PRO Tor & VPN Router

    PRO is the most advanced way to fortify your privacy and online anonymity by layering the Tor network with VPN services. Use both together or separately, and without needing to download software onto your devices.

    Phishing is at the top of most security top 10 efforts you should be pursuing in 2016 and beyond. If you don't have phishing incorporated into your Security Awareness Program yet, now is the time. Phishers, and the scams they use, are only going to …
    Are you using email marketing software? If not, you're missing out on effortless marketing and the reaching of desired conversion rates through email marketing software.
    Need more eyes on your posted question? Go ahead and follow the quick steps in this video to learn how to Request Attention to your question. *Log into your Experts Exchange account *Find the question you want to Request Attention for *Go to the e…
    Excel styles will make formatting consistent and let you apply and change formatting faster. In this tutorial, you'll learn how to use Excel's built-in styles, how to modify styles, and how to create your own. You'll also learn how to use your custo…

    933 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    19 Experts available now in Live!

    Get 1:1 Help Now