Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you tell if the user hit cancel during a download from a Java servlet?

How can you tell if the user hit cancel during a download from a Java servlet? What seem to happen for me with IE, the output stream println() blocks. The used hit cancel, but is there a way to time this out or anything like that?

like image 833
GC_ Avatar asked Sep 09 '10 18:09

GC_


2 Answers

Wrap OutputStream#write(), #flush() and #close() in a try-catch block on IOException. If caught, then it usually means that the enduser has aborted the request.

To get a step further, you could also catch on a more servletcontainer-specific exception like ClientAbortException on Tomcat and clones (which is a subclass of IOException), but this will make your webapp code unportable to other servletcontainers.


Update: to come back on the blocking issue, you'd like to call flush() after writing a single block of data. This will actually send the data to the client and cause IOException when the underlying socket is closed.

like image 141
BalusC Avatar answered Oct 13 '22 10:10

BalusC


You won't be able to tell for sure. It depends on how your servlet container is implemented.

When the user hits "Cancel", the browser should close the socket. This will be detectable by the server, of course, but whether the server has the ServletOutputStream "plumbed" directly to the socket's OutputStream is implementation-dependent. If it does, an IOException will be raised the next time the servlet attempts to write data.

If the container buffers output, the servlet might just finish writing data and never know anything went amiss.

like image 44
erickson Avatar answered Oct 13 '22 11:10

erickson