Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finishing a 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 response code (or other) after accepting the incoming parameters.

Is there a way for a HttpServlet to complete the http request/response handshake and yet continue processing?

Something like...

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

EDIT: Looking at the javax.servlet package - the proper phrasing to my question is

How do I commit a response?

as in Servlet.isCommitted()

like image 304
Stevko Avatar asked Mar 02 '10 23:03

Stevko


People also ask

Should I close HttpServletResponse Outputstream?

The general rule of them is this: if you opened the stream, then you should close it. If you didn't, you shouldn't. Make sure the code is symmetric. In the case of HttpServletResponse , it's a bit less clear cut, since it's not obvious if calling getOutputStream() is an operation that opens the stream.

What is Httpservlet response?

public abstract interface HttpServletResponse extends ServletResponse. Defines an HTTP servlet response that a servlet running on a Web server sends to a client using HTTP. This interface allows the servlet's service method to access HTTP headers and return data to its client.

What is the difference between HttpServletRequest and HttpServletResponse?

HttpServletRequest "extends the ServletRequest interface to provide request information for HTTP servlets." HttpServletResponse "extends the ServletResponse interface to provide HTTP-specific functionality in sending a response. For example, it has methods to access HTTP headers and cookies."

How to forward a request in Servlet?

We get hold of RequestDispatcher reference from parent Servlet and point it to another server resource. Simply put, this will forward the request. When a client submits a request to http://localhost:8081/hello?name=Dennis, this logic will run and the request will be forwarded to “/forwarded“.


1 Answers

Here's how I've handled this situation:

  1. When the app starts up, create an ExecutorService with Executors.newFixedThreadPool(numThreads) (there are other types of executors, but I suggest starting with this one)
  2. In doPost(), create an instance of Runnable which will perform the desired processing - your task - and submit it to the ExecutorService like so: executor.execute(task)
  3. Finally, you should return the HTTP Status 202 Accepted, and, if possible, a Location header indicating where a client will be able to check up on the status of the processing.

I highly recommend you read Java Concurrency in Practice, it's a fantastic and very practical book.

like image 118
Avi Flax Avatar answered Sep 23 '22 10:09

Avi Flax