RequestDispatcher - when is the response received?

I am writing basic code when I find out about RequestDispatcher. I understand that when rd.forward () is called, control (and response processing) is transferred to the resource named in the path - in this case, another servlet. But why doesn't this code throw an IllegalStateException (not what I want) because of the out.write () statements earlier in the code?

I assume I am really asking how and when will these out.write () statements be executed?

Thanks Jeff

public class Dispatcher extends HttpServlet{ public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException{ response.setContentType("text/plain"); PrintWriter out = response.getWriter(); out.write("In Dispatcher\n"); String modeParam = request.getParameter("mode"); String path = "/Receiver/pathInfo?fruit=orange"; RequestDispatcher rd = request.getRequestDispatcher(path); if(rd == null){ out.write("Request Dispatcher is null. Please check path."); } if(modeParam.equals("forward")){ out.write("forwarding...\n"); rd.forward(request, response); } else if(modeParam.equals("include")){ out.write("including...\n"); rd.include(request, response); } out.flush(); out.close(); } 

}

+6
source share
3 answers

Because you did not call flush .

Everything will be cleaned before shipment if you have not blushed. Otherwise, you will receive the prescription that you expect.

Like in docs:

For RequestDispatcher received via getRequestDispatcher (), the ServletRequest object has its own path elements and parameters adjusted to match the path of the target resource.

the forward must be called before the response is transmitted to the client (before the response body was discarded) . If the answer has already been completed, this method is IllegalStateException. Invalid output in the response buffer is automatically cleared before proceeding.

+4
source

Read the docs .

A call to flush() in PrintWriter completes the response.

Now, according to your curiosity, why there is no IllegalStateException . This is simply because PrintWriter.flush() does not throw this or any checked exception. And we know that the answer was not fixed when rd.forward() was called, since flush() comes later in the method.

+3
source

You did not make flush () call before moving on. Thus, this does not show any exceptions. If you write flush () before sending the request, it will throw an exception.

When we call flush (), everything that was in the buffer is sent to the browser, and the buffer is cleared.

In the following scenario, we will get an exception.

 response.getWriter().print('hello...'); response.getWriter().flush(); request.getRequestDispatcher("/index.").forward(request, response); 
+1
source

Source: https://habr.com/ru/post/951697/


All Articles