Basically, you'd like to store a reference to the task and inherently also its progress in the HTTP session (or in the Servlet context if it concerns an application wide task). This way you must be able to retrieve information about it on every HTTP request.
In JavaScript, you can use setTimeout()
or setInterval()
to execute a function after a certain timeout or at certain intervals. You can use this to repeatedly fire Ajax requests to request current status of the progress. Once the status is retrieved, e.g. in flavor of an integer with a max value of 100 (the percentage), just update some div representing a progressbar and/or the percentage text accordingly in the HTML DOM tree.
jQuery is very helpful in firing ajaxical requests and traversing/manipulating the HTML DOM tree like that. It minimizes the code verbosity and crossbrowser compatibility headaches.
Imagine that the doGet()
of the servlet look like this:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String processId = "longProcess_" + request.getParameter("processId");
LongProcess longProcess = (LongProcess) request.getSession().getAttribute(processId);
int progress = longProcess.getProgress();
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(String.valueOf(progress));
}
Then you can use it like follows:
function checkProgress() {
$.getJSON('progressServlet?processId=someid', function(progress) {
$('#progress').text(progress + "%");
$('#progress .bar').width(progress);
if (parseInt(progress) < 100) {
setTimeout(checkProgress, 1000); // Checks again after one second.
}
});
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…