Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Controller start processing after response is sent

I am using a Spring MVC controller and want to start the execution of a task in a new thread. However the task should not start immediately but only after the response has been sent to the client.

The sequence - in strict temporal order:

  1. request
  2. return new ResponseEntity ... / client receives HTTP status 200 OK.
  3. processing of the task begins.

How do I achieve this?

I wanted to use Spring's async abstraction by calling a method annotated with @Async, but it does not guarantee that the new thread waits for the response to be sent first.

like image 841
mreiterer Avatar asked Dec 16 '14 15:12

mreiterer


1 Answers

You can use an interceptor for that. The order of events for handling a request in Spring MVC is:

  • DispatcherServlet get a Request, Response pair and determines the handling
  • [optional] interceptors preHandle are called (with option to stop processing)
  • controller is called
  • [optional] interceptors postHandle are called
  • ViewResolver and view do the actual Response processing and send the response
  • [optional] interceptors afterCompletion are called

The above is over simplified and is just aimed at showing that interceptor afterCompletion methods are called after the response has been sent to client, with following signature :

void afterCompletion(HttpServletRequest request,
                     HttpServletResponse response,
                     Object handler,
                     Exception ex)
                     throws Exception

In that method, you can test the occurence of an exception and the correctness of the response (ex == null && response.getStatus() == HttpServletResponse.SC_OK) before starting your processing.

like image 108
Serge Ballesta Avatar answered Sep 19 '22 11:09

Serge Ballesta