?
Solved

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

Posted on 2004-10-28
13
Medium Priority
?
977 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
Comment
Question by:wizlokesh
  • 6
  • 3
10 Comments
 
LVL 35

Accepted Solution

by:
TimYates earned 200 total points
ID: 12431745
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
petmagdy earned 200 total points
ID: 12431751
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
ID: 12431758
If u want to forward to JSP after finishing download use sendRedirect
0
[Webinar] Improve your customer journey

A positive customer journey is important in attracting and retaining business. To improve this experience, you can use Google Maps APIs to increase checkout conversions, boost user engagement, and optimize order fulfillment. Learn how in this webinar presented by Dito.

 
LVL 35

Expert Comment

by:TimYates
ID: 12431782
>  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
ID: 12431786
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
ID: 12431846
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
ID: 12431914
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
ID: 12433292
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
ID: 12433351
I think the idea is to go to a different page once the download is complete...
0
 
LVL 35

Expert Comment

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

so I reckon a split between TimYates and petmagdy
0

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Custom Android App Development is the need of an hour for several businesses. If you go through the right firm for Android Application Development, it can make a huge difference to the ways in which customers interact with your business.
Cloud is selling like hotcakes in the town. Technology lovers and even businesses have joined the wagon to taste a piece of this delicious technology treat. But how many of us really know what cloud is?
Hi, this video explains a free download that you can incorporate into your Access databases, or use stand-alone for contact management. Contacts -- Names, Addresses, Phone Numbers, eMail Addresses, Websites, Lists, Projects, Notes, Attachments…
Free Data Recovery software is an advanced solution from Kernel Tools to recover data and files such as documents, emails, database, media and pictures, etc. It supports recovery from physical & logical drive after a hard disk crash, accidental/inte…
Suggested Courses
Course of the Month4 days, 23 hours left to enroll

601 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