In servlet Filters, filterChain.doFilter(request, response); should pass the request to next one in chain.
But consider the following two codes:
Code 1:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException
{
filterChain.doFilter(request, response);
try
{
Thread.sleep(20000);
}
catch(Exception e)
{
}
}
Code 2:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException
{
try
{
Thread.sleep(20000);
}
catch(Exception e)
{
}
filterChain.doFilter(request, response);
}
Both the filters executes as same. i.e. Both takes 20 seconds before serving the request.
But actually what should happen is Code1 should serve inmmediately and Code2 should serve after 20 seconds.
Why this ambiguity in Filter?
Sleeping in servlet or in filter is always a bad idea because HTTP worker threads are scarce resources, thus you shouldn’t block them. But in your particular example there is hope.
Basically whatever you print in your servlet or filter to the output is implicitly buffered to improve performance. If you print enough data inside servlet/filter, servlet container will flush the buffer and parts of your response will reach the client. But you can also flush manually!
flushBuffer()instruction forces the container to flush the output buffer. All response headers and whatever you sent from the servlet is sent to the client. But here’s the catch: the client will receive the data but the HTTP connection remains open for the next 20 seconds. I tested this withcurland it works as expected. But when the same URL is used in the browser (tested on Opera, Firefox and Google Chrome), the browser waits 20 seconds before displaying anything (this may be dependent on what you actually send).