The key difference between the two is that
the forward() method will CLOSE the output stream after it has been invoked,
whereas the include method leaves the output stream OPEN.
answering with an example :
lets have a servlet page named xxx.java and a jsp page named yy.jsp
In the yy.jsp
WELCOME to yy.jsp
In the xxx.java //using forward()
RequestDispatcher rd = request.getRequestDispatcher("yy.jsp");
rd.forward(request,response);
out.println("back to servlet"); //this wont b displayed
output
WELCOME to yy.jsp
In the xxx.java //using include()
RequestDispatcher rd = request.getRequestDispatcher("yy.jsp");
rd.include(request,response);
out.println("back to servlet");
output
WELCOME to yy.jsp back to servlet
BUT MOST IMPORTANTLY ITS NOT ABOUT THE CONTROL, BECAUSE IF WE PUT a
System.out.println("console output");
after either of the .forward()
or .include()
invocation, the console output will get generated on each case.Its about the response to the client
So, the basic part is
if we are processing in a server side component and then forward to a JSP or Servlet in order to generate markup for a client, once that JSP or Servlet has finished processing, we can no longer call on any other components to generate markup that can be sent to the client. Once we have performed a forward, markup generation for the current request and response cycle is finished.
Alternatively, with an include, the output stream remains open, so we can call on as many different files to generate client side markup that we need. So we can include two or three JSP files and even a Servlet in the chain of components that generate client based markup. When we use an include, the output stream is not closed after invocation.