在Spring MVC 3.2中,我创建了一个带有textarea的(JSP)网页。从客户端我启动一个在服务器上执行的控制台应用程序。我想在浏览器的textarea中显示此控制台应用程序的输出。
我得到一个响应,显示控制台的cmd输出。但问题是程序完成后会立即显示控制台输出。我想看到每个输出行立即更新textarea。
控制器代码
@RequestMapping(value = "/url", method = RequestMethod.POST)
public void Console(HttpServletResponse response) throws Exception {
Process p = Runtime.getRuntime().exec("cmd /C cd \"C:\\appl\"" + "&" + "consoleApp.bat");
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
response.getWriter().println(line);
response.getWriter().flush();
logger.info(line);
}
}
客户代码
$(function(){
$('#someTag').click(function(){
$.post("url","data",
function(response){
$('#console').append(response);
var psconsole = $('#console');
psconsole.scrollTop(
psconsole[0].scrollHeight - (psconsole.height() - 10)
);
});
});
});
我实施了一个轮询机制(见下面的代码)。然而,这是我想到的更间接的方法。如果有人得到更清晰的实现或简单的服务器推送示例,我希望看到它。
控制器代码
@RequestMapping(value = "/deploy", method = RequestMethod.POST)
public @ResponseBody String console(@RequestParam(value="request", required=false) String request) throws Exception {
logger.info("status " + request);
if(request.equals("start")){
Process p = Runtime.getRuntime().exec("cmd /C dir C:\\");
in = new BufferedReader(new InputStreamReader(p.getInputStream()));
return "started";
}
while ((line = in.readLine()) != null) {
logger.info(line);
return line;
}
logger.info("status finished");
return "finished";
}
客户代码
var status = "start";
var console = $('#console');
console.append("starting" + '\r');
(function poll(){
setTimeout(function(){
$.ajax({
url: "deploy",
data: {request: status},
type: "post",
success: function(data){
if(data.indexOf("finished") !== -1){
console.append(data + '\r');
setTimeout(function()
{console.scrollTop(console[0].scrollHeight - console.height());}
, 20);
status = "finished";
}else if(data === ""){
console.append('\r');
setTimeout(function()
{console.scrollTop(console[0].scrollHeight - console.height());}
, 20);
status = "processing";
poll();
}else{
console.append(data + '\r');
setTimeout(function()
{console.scrollTop(console[0].scrollHeight - console.height());}
, 20);
status = "processing";
poll();
}
}, dataType: "text"});
}, 100);
})();