所以在前端主页中有一个我可以打开和关闭的开关。可以使用Ajax将开关的状态代码发送到后端。
现在,当开关打开时,我希望后端方法继续运行,我定义如下:
public static void foo {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
while(true) {
try {
Thread.sleep(8000);
ArticleDAO.addNewArticles();
} catch (Exception e) {
e.printStackTrace();
}
}
}
});
thread.start();
}
当开关关闭时,我希望终止该方法或线程。
JSP页面中的Ajax代码如下所示:
$("#switcher").on("switchChange.bootstrapSwitch", function(e, state) {
if (state == true) {
$(function() {
$.ajax({
type: "POST",
url: "http://localhost:8080/wx/admin/toggle_state.html",
data: {
stateCode: 1
},
success: function(data) {
alert("Switched to auto mode");
},
error: function() {
alert("Something went wrong!!");
}
});
});
} else if (state == false) {
$(function() {
$.ajax({
type: "POST",
url: "http://localhost:8080/wx/admin/toggle_state.html",
data: {
stateCode: 0
},
success: function(data) {
alert("Switched to manual mode");
},
error: function() {
alert("Something went wrong!!");
}
});
});
} else {
alert("Something went wrong!!");
}
});
这是 Spring Controller :
@RequestMapping(value = "admin/toggle_state.html", method = RequestMethod.POST)
@ResponseBody
public String toggleState(@RequestParam Integer stateCode) throws Exception {
if (stateCode == 1) {
/*
EXECUTE THE FOO METHOD RIGHT HERE
*/
System.out.println("Switched to auto mode.");
} else if (stateCode == 0) {
// TERMINATE THE METHOD / THREAD HERE
}
return "";
}
那么实现这一目标的推荐方法是什么?实际上看起来并不太难,但我不知道在我的情况下如何启动和终止线程。我能想到的一种方法是将开关的状态代码存储到数据库中,并使该方法每次在线程中运行时都检查数据库。但这似乎并不是一个很好的解决方案。有任何想法吗?提前致谢!!
最佳答案
添加一个 bean(应用程序范围)以保留对线程的引用。将 bean 自动连接到 Controller 。
检查stateCode值并使用bean的引用来start()/stop()线程。
@Component
public ThreadHolderBean {
Thread theThreadReference=new Thread();//init the thread properly
}
现在在你的 Controller 中添加
@Autowired
private ThreadHolderBean threadHolder;
并在toggleState()方法中使用threadHolder
如果您需要多个线程,例如每个 session ,请更改 bean 范围或定义线程池。
关于java - Spring MVC : triggering and terminating a backend method by turning on and off a switch on a web page,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28455788/