How do I setup a page to contiunually update as results are coming in from my java servlet?

Go To StackoverFlow.com

0

I am new with jQuery and I'm having a hard time getting my page to continually update as results come in from my java servlet. I want like a timer effect on the web page as new time values are coming in from the servlet.

On my webpage I have something like this:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.js"></script> 
<script>$(document).ready(function(){$.get("/timer", function(data){$('H1').append(data);  })})(); </script>

And in my servlet timer I have a while loop that uses the response.getWriter() to write the new time value for like 30 iterations:

//this is in my doGet function
while(count <30 ){
count++;
out.println(count);
}

The problem is when I load the page nothing gets appended to the page until the 30 iterations are done. Is there a way to get each it iteration print out to show on the page?

Thanks

2012-04-04 01:35
by Rehat


1

out.flush() will write whatever is in the buffer to the browser.

Remember though that if you have a long running server operation, you may need a better mechanism so that the server knows when client goes away/stops the operation so that server can stop the processing too. Also, you can have a better user experience by not needing to navigate to another page, by leveraging javascript

Typically, a javascript timer/poll is used to obtain status of the operation (on the server, you may have the operation running on a separate thread - this also serves as a keep-alive message to the server - if the server does not receive a alive, it may want to stop the processing for efficiency )

Long polling and html5 web socket (you will need support on the server for web socket) are other approaches -

see: http://techoctave.com/c7/posts/60-simple-long-polling-example-with-javascript-and-jquery

2012-04-04 01:46
by Vijay Agrawal
is this a limitation with using java servlet? I want to get the same effect as this site when doing a domain search: linkRehat 2012-04-04 02:02
No it isnt. You can do something like the site you sent with Java too. Try doing out.flush() - this will print to the browser. Note though that in the example site you sent, when you click on 'search', it sends a new request and navigates to a new pag - Vijay Agrawal 2012-04-04 02:19
i have edited my answer with the updates from the comment abov - Vijay Agrawal 2012-04-04 03:08
Ads