按钮 onClick 调用 Java 方法直到出现特定结果
我对 Spring 框架(以及大多数 Web 开发)完全陌生,但我正在尝试将一些繁重的 Java 后端代码连接到新的 Spring 和 JSP 项目。我的控制器的 handleRequest()
在返回我的 request.jsp ModelAndView
对象之前启动一个长时间运行的工作线程。之后,我希望仍然能够从 JSP 表单与该控制器进行交互,以便每当单击表单中的按钮时都能够调用控制器中的 isThreadDone()
。根据三个不同的结果,我会相应地重定向。我目前的方法可以做到这一点吗?这似乎违反了 Spring MVC 的一些方法,但我想不出一个可以解决这个问题的好方法。如果这里有什么不对劲的地方,请原谅我的无知。提前致谢。
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 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
看一下 Spring
@Async
注释。如果您使用该注释来注释 Service 层 bean,那么它就会在自己的线程中运行,从而允许您的 Controller 线程在调用 Service 方法后不间断地运行。通过同步方法将该线程设置为服务的类级别保存的值,并且您的控制器代码可以随意检查这些切换以查看该过程是否完成。类似于:在控制器中:
如果多个请求可能会启动该进程,那么我会将每个
isDone
切换保存在具有某种标识符的 HashMap 中。然后,线程将更新各个切换,每个请求对应一个切换。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 viasynchronous
methods, and your Controller code can just check those toggles at will to see if the process is done or not. Something like:In the Controller:
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.嗯,一切皆有可能,对吧?根据您提供的内容,您可以保留对线程的引用(可能在 HttpSession 中),以便当单击按钮收到新请求时,您可以查询它并返回适当的响应。
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.