What I am trying to accomplish is not too complex, but I am having a bit of trouble as I am not well versed in AJAX.
When it is implemented, I will have a JSP that has a button which invokes an Asynchronous Servlet. The servlet will run a long running task and provide dynamic feedback to the user by adding rows to a table when parts of the task are completed.
Before I attempt to write the final version, I am doing a proof of concept to get an understanding of how this will work. However, I'm running into a snag. When I use an AJAX call upon clicking a button, the function works as expected when the call is to a regular synchronous servlet. However, as soon as I make the servlet asynchronous, the updates are not displayed.
Would anybody be able to provide some insight into what's going wrong?
My JSP looks like this:
<html>
<body>
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
$('#mybutton').click(function() {
$.get('someservlet', function(responseJson) {
$.each(responseJson, function(index, item) {
$('<ul>').appendTo('#somediv');
$('<li>').text(item.row1).appendTo('#somediv');
$('<li>').text(item.row2).appendTo('#somediv');
$('<li>').text(item.row3).appendTo('#somediv');
$('<li>').text(item.row4).appendTo('#somediv');
});
});
});
});
</script>
<p><button id="mybutton">Click to add things</button></p>
<div id="somediv"></div>
</body>
</html>
My Asynchronous Servlet doGet()
method looks like this:
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
final AsyncContext asyncContext = request.startAsync();
final PrintWriter writer = response.getWriter();
asyncContext.setTimeout(10000);
asyncContext.start(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
List<Row> rows = new ArrayList<Row>();
rows.add(new Row(i, i + 1, i + 2, i + 3));
String json = new Gson().toJson(rows);
writer.write(json);
writer.flush();
log.info("Wrote to JSON: " + i);
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
}
}
asyncContext.complete();
}
});
Any thoughts? It seems like my AJAX call that occurs when I click the button only accepts a response from the main servlet thread. Perhaps I need to call a JavaScript function from the asynchronous write()
calls? I'm just not sure how to do this or if this would be the correct method of execution.