javaservletsdownloadrequest-cancelling

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?


Solution

  • 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.