duncanportelli
duncanportelli

Reputation: 3229

Continue JSP execution after sending HTTP response

How can I have a JSP page send a HTTP response to the client, and then keep executing?

I have a JSP page that has to execute a long request which generates a report with large amounts of data and saves it to disk. This normally takes minutes to complete. This JSP page is called by an application that I have no control over.

This application has a timeout delay shorter than 45 seconds and therefore each request to a JSP page is resulting in a timeout. Therefore, I need the JSP page to send the complete HTTP response to the client as fast as possible (ideally, as soon as the input parameters have been validated), and then run the process to generate the report and saving it to disk afterward.

Should I open a separate thread to generate the report? This way, the response is sent back to the client, while the thread is still running. Is there any other way with which I can achieve this?

Upvotes: 0

Views: 633

Answers (1)

user2023577
user2023577

Reputation: 2121

A JSP is a view, not a controller. It is not the preferred place to perform work.

By definition, the JSP bytes are the output, so you cannot expect to do synchronous (on same thread) work in java directive tags after the end of the jsp. Well, unless you prematurely close the response in a java directive tag... But that is unclean (expect trashing your server logs with error messages...)

The spun thread trick only works if you can even start a thread (not all container would allow that). And if you can, you run into the risk of attacks; you would need to control how many threads are allowed. That means having a pool in the context, and implementing a fail-fast if all threads are busy.

This can take the form of a ThreadPoolExecutor (that you woul dlazily install in the servlet context), constructed with a blockingqueue with a small limit, to which you submit() your task but handling that it can be rejected (and failing with a suitable message to the user).

Read carefully the Queueing part of the ThreadPoolExecutor.

Of course, you can toy with onTimer() on the javascript side to pool for the progress, or to cancel (all that with a token in the session for the running task of course).

Upvotes: 1

Related Questions