Button onClick Call Java Method Until Certain Result
I'm completely new to the Spring framework (and most web development in general), but I'm trying to hook up some heavy Java backend code to a new Spring and JSP project. My Controller's handleRequest()
is kicking off a long running worker thread before it returns my request.jsp ModelAndView
object. After that I'd like to be able to still interface with this Controller from my JSP form to be able to call isThreadDone()
in the Controller whenever a button in the form is clicked. Based on three different results, I then redirect accordingly. Is this possible with my current approach? This seems to violate some of the Spring MVC approach, but I 开发者_Go百科can't think of a good way to do this that I can wrap my head around. If anything is way off here, please excuse my ignorance. Thanks in advance.
Take a look at the Spring @Async
annotation. If you annotate a Service-layer bean with that annotation, it then runs in its own thread, allowing your Controller thread to run without interruption after calling the Service method. Have that thread is set a value held at the Class level for the Service via synchronous
methods, and your Controller code can just check those toggles at will to see if the process is done or not. Something like:
@Service
public myServiceClass {
private boolean isDone = false;
public synchronized void setIsDone(boolean isDone) {
isDone = isDone;
}
public synchronized boolean getIsDone() {
return isDone;
}
@Async
public void myServiceMethod() {
...long-running stuff...
setIsDone(true);
}
In the Controller:
@Controller
class MyController {
@RequestMapping
public kickOffHandlerMethod() {
myServiceClass.myServiceMethod();
}
}
@RequestMapping
public dependentHandlerMethod() {
if(myServiceClass.getIsDone()) {
...do something...
}
}
}
If more than one request might kick off the process, then I would save each isDone
toggle in a HashMap with some kind of identifier. Then the threads would update individual toggles, one for each request.
Well, anything is possible, right? Based on what you've provided, you can just keep a reference to the thread--maybe in the HttpSession--so that when a new request comes in from clicking the button, you can query it and return an appropriate response.
精彩评论