I needed to output some sort of data with a delay on JSP. I've done it in the next way:
for (int i = 0; i < arr.length; i++) {
out.println(arr[i] + " ");
out.flush();
Thread.sleep(100 * i);
}
And І've got the expected result (data was output with delays). Then, I've tried to forward to another JSP, using that approach:
<% out.println("Hello there.");
out.flush(); %>
<jsp:forward page="/another.jsp"></jsp:forward>
and it didn't worked for me (JSP wasn't forwarded). However, forwarding in that way without dealing the out.flush() is working fine. What is the problem and how can I forward to another JSP after showing some data with the current one?
I suspect jsp:forward
doesn't work because it tries to use an HTTP 3xx response, but the flush()
causes your JSP to send an implicit HTTP 200
, so the 3xx
doesn't get sent.
Any given HTTP request -- like the one you make to test your webpage -- can have at most 1 HTTP response from the server. The HTTP response must be sent before any actual output can happen. (So, you can't send "hello"
followed by the HTTP response; the HTTP response has to come first.) When you called flush()
, you forced the JSP to send any pending output. Since no header had been sent at that time, the JSP sent an implicit HTTP 200, then sent the output.
If you want to send output and then redirect afterwards, you'll need to use a browser-side redirect.
There are a couple of options you can use:
<script>
setTimeout(function() {
document.location = "/next/page/to/go/to.jsp";
}, 1000); // <-- this is the delay in milliseconds
</script>
You can put this anywhere on your page. It's a JavaScript snippet that instructs the browser to go to a new location after a fixed delay. It only works for browsers with JavaScript enabled, but that's about 99.99% of the world nowadays, so don't worry too much about that. :)
The setTimeout
call means you always redirect after a fixed delay. You could easily use an AJAX call or a websocket event (or 100 other things) to trigger the redirect too, assuming your application is willing to assume those are available in the target browser.
This is probably the preferred method.
<head>
of your page:<meta http-equiv="refresh" content="1; url=/next/page/to/go/to.jsp">
This is an older (but very well-supported) technique for forcing a webpage to refresh or redirect after a fixed delay. This snippet uses 1 second, just like the previous snippet, but it's very easy to change.
The technique is kind of frowned upon these days, but still works.