How do I download a text file from a servlet onto a client m/c


Web tier: servlets, JSP, Web frameworks: How do I download a text file from a servlet onto a client m/c

  1. Hi,
    I have to download files from the server on to the client machine,

    I have written the code, which gives the dialog box asking for location to download the file to on the client machine, after giving the file name and location and then pressings save,
    It saves the file but gives the following errors,

    1) The IE browser ends up thinking it still is waiting on something, so the hourglass never goes away, and the globe keeps on spinning.
    2) Secondly the other links on that page becomes unoperational., and if I click on any other links it gives the error IllegalStateException: response is already committed.

    The code is shown below :

    response.setContentType ("application/x-filler");
    response.setHeader ("Content-Disposition", "attachment;filename=abc.txt"");
    ServletOutputStream op = response.getOutputStream ();
    while ((in != null) && ((length = != -1))
    // the data has already been read into buf

    String uri = "/HelloWorld.jsp";
    RequestDispatcher dispatcher = getServletConfig().getServletContext().getRequestDispatcher(uri);

    Urgent!!! please help...

  2. I believe the problem is that you are trying to get the JSP-RequestDispatcher AFTER you have closed the response object's output stream. I reckon that throws an IllegalStateException or something like that...
  3. You cannot use the forward() method if you have already defined a PrintWriter or ServletOutputStream object. In your case you have already opened and closed ServletOutputStream. if this is the case, forward() throws an IllegalStateException.

    For more information read Java APIs for RequestDispatcher.
  4. Thanks for giving the replies, but could you please tell me how can I forward the request after writing the file on the client machine.

  5. Hi Raswal-

    I think your problem lies in a misunderstanding of the lifecycle of a request.

    Once you have closed your response object, you cannot write any more out put to it.

    When you do a requestdispatcher.forward() it does not create a new request + response, it uses the current one.

    Hence there is no point doing a requestdispatcher.forward() after you have closed the response, since you wouldn't be able to write anything anyway.

    If what you want to do is redirect to another page once the download is complete, then I imagine some fancy Javascript may be able to do this, but I cannot think of anyway to do it on the server side.