What I'm trying to accomplish is not too complicated, but I have a bit of a problem as I am not very good at AJAX.
When it is implemented, I will have a JSP that has a button that invokes the asynchronous servlet. The servlet will perform the long-term task and provide dynamic feedback to the user by adding rows to the table when the parts of the task are completed.
Before I try to write the final version, I make a proof of concept to understand how this will work. However, I am facing a problem. When I use an AJAX call when I click the button, the function works as expected when the call is made for a regular synchronous servlet. However, as soon as I make the servlet asynchronous, updates are not displayed.
Can anyone give some idea of what is 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 is as follows:
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 that my AJAX call, which occurs when I click the button, only accepts the response from the main servlet thread. Perhaps I need to call a JavaScript function from asynchronous calls write()? I'm just not sure how to do this, or if this will be the correct execution method.