我正在尝试在服务器上为长时间运行的进程实施解决方案,在该服务器上处理 pdf 生成请求大约需要 10 分钟。浏览器在 5 分钟内无聊/超时。我正在考虑使用 Ajax 和线程来处理这个问题。我正在为 ajax 使用常规 javascript。但我坚持下去。
我已经到达了将请求发送到 servlet 并且 servlet 启动线程的地步。请参阅下面的代码
public class HelloServlet extends javax.servlet.http.HttpServlet
implements javax.servlet.Servlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("POST request!!");
LongProcess longProcess = new LongProcess();
longProcess.setDaemon(true);
longProcess.start();
request.getSession().setAttribute("longProcess", longProcess);
request.getRequestDispatcher("index.jsp").forward(request, response);
}
}
class LongProcess extends Thread {
public void run() {
System.out.println("Thread Started!!");
while (progress < 10) {
try { sleep(2000); } catch (InterruptedException ignore) {}
progress++;
}
}
}
这是我的 AJax 调用
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html><head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>My Title</title>
<script language="JavaScript" >
function getXMLObject() //XML OBJECT
{
var xmlHttp = false;
xmlHttp = new XMLHttpRequest(); //For Mozilla, Opera Browsers
return xmlHttp; // Mandatory Statement returning the ajax object created
}
var xmlhttp = new getXMLObject(); //xmlhttp holds the ajax object
function ajaxFunction() {
xmlhttp.open("GET","HelloServlet" ,true);
xmlhttp.onreadystatechange = handleServerResponse;
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send(null);
}
function handleServerResponse() {
if (xmlhttp.readyState == 4) {
if(xmlhttp.status == 200) {
document.forms[0].myDiv.value = xmlhttp.responseText;
setTimeout(ajaxFunction(), 2000);
}
else {
alert("Error during AJAX call. Please try again");
}
}
}
function openPDF() {
document.forms[0].method = "POST";
document.forms[0].action = "HelloServlet";
document.forms[0].submit();
}
function stopAjax(){
clearInterval(intervalID);
}
</script>
</head>
<body><form name="myForm">
<table><tr><td>
<INPUT TYPE="BUTTON" NAME="Download" VALUE="Download Queue ( PDF )" onclick="openPDF();">
</td></tr>
<tr><td>
Current status: <div id="myDiv"></div>%
</td></tr></table>
</form></body></html>
但我不知道如何进一步进行,例如线程如何与浏览器通信该进程已完成,以及 ajax 应如何调用我并检查请求的状态。
如果我遗漏了一些片段,请告诉我。任何建议,如果有帮助。