Execute a task after the modelAndView is returned
In Spring, is there a way to execute a task after returning a view or I need to create a ThreadPool and do it ?
Ex:
public ModelAndView handleRequest(H开发者_StackOverflowttpServletRequest request,
HttpServletResponse response) throws Exception {
Map<Object, Object> data = new HashMap<Object, Object>();
//do some stuff
executeSomeStuffButDontWaitForTheResult();
return new ModelAndView("result", data);
}
If you're using Spring 3, the easiest way to do this would be to annotate your executeSomeStuffButDontWaitForTheResult method with @Async.
In your configuration:
<task:annotation-driven executor="yourTaskExecutor" scheduler="yourTaskScheduler"/>
For more info here
Spring contains an Aspect Oriented Programming framework which allows you to specify code to be run before and after various parts of your code that may be the kind of thing you are looking for. Take a look at the Spring documentation: Aspect Oriented Programming with Spring.
If you really don't want to wait for the result, you should run it in a different thread anyways. For example, using Spring's Task Executor.
You can use a Task Executor like @axtavt said or you could use Asynchronous JMS
Yup, this is just a matter of either spawning a thread or (better) grabbing a thread from a pool. It has nothing to do with Spring.
But in looking at your code, you're leaving open the possibility that the view is just going to render a partially populated or even empty map. (And if you don't pass the map to the executeSomeStuffButDontWaitForTheResult() method, it is guaranteed that the map will be empty.) It's not clear what you're attempting to do, but I doubt you intend to return a partial or empty map, and the map isn't going to fill up while the user is looking at the web page. If you describe more carefully what you're trying to do we might have some alternative ideas for you.
精彩评论