End HttpServletResponse, but continue processing

I have a situation that seems to fit the Async Servlet 3.0 / Comet situation, but all I need to do is return a 200 (or other) response code after accepting the input parameters.

Is there a way for the HttpServlet to complete the hash of the HTTP request / response and continue processing?

Something like...

doPost( req, response ) { // verify input params... response.setStatus( SC_OK ); response.close(); // execute long query } 

EDIT: Look at the javax.servlet package - the correct wording of my question is -

How do I complete the answer?

as in Servlet.isCommitted ()

+6
java servlets comet
source share
4 answers

Here's how I dealt with this situation:

  • When the application starts, create an ExecutorService using Executors.newFixedThreadPool(numThreads) (there are other types of executors, but I suggest starting with this one)
  • In doPost() create a Runnable instance that will perform the required processing β€” your task β€” and submit it to ExecutorService like this: executor.execute(task)
  • Finally, you should return the 202 Accepted HTTP status and, if possible, the Location header, indicating where the client will be able to check the processing status.

I highly recommend you read Java Concurrency in practice , this is a fantastic and very practical book.

+6
source

You can continue processing in a separate thread.

The response ends after returning from the doPost() method.

+3
source

If possible, for your servlet, accept a request for processing in the background, for a servlet, transfer processing to a separate thread, which then runs in the background.

Using Spring, you can invoke a separate thread using TaskExecutor . The advantage of using spring over the standard JDK 5 java.util.concurrent.Executor is that if you are on application servers that need to use managed threads (IBM websphere or Oracle weblogic), you can use WorkManagerTaskExecutor to connect to the work of CommonJ managers .

Another alternative would be to move the long request logic into a Message Driven Bean or Message Driven POJO ( Spring JMS can help here) and let the servlet just put the message in the JMS queue. This will have the advantage that if the loading of your web container becomes too large due to your long request, you can easily move the MDB to another (dedicated) system.

+3
source

This example may help.

 void doPost(){ // do something final ExecutorService executor = Executors.newSingleThreadExecutor(); executor.execute(new Runnable() { @Override public void run() { // processing after response } });} 
0
source

All Articles