Junior developers often get confused between the include and the forward methods of the RequestDispatcher. The key difference between the two is the fact that the forward method will close the output stream after it has been invoked, whereas the include method leaves the output stream open.
By submitting your email address, you agree to receive emails regarding relevant topic offers from TechTarget and its partners. You can withdraw your consent at any time. Contact TechTarget at 275 Grove Street, Newton, MA.
Why does this matter? Well, if you are doing 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, you can no longer call on any other components to generate markup that can be sent to the client. Once you have performed a forward, markup generation for the current request and response cycle is finished.
Alternatively, with an include, you the output stream remains open, so you can call on as many different files to generate client side markup that you need. So you can include two or three JSP files and even a Servlet in the chain of components that generate client based markup. When you use an include, the output stream is not closed after invocation.
Of course, it sounds nice to have an open stream, and be able to call includes on multiple resources, but this typically is not a good practice. Having a server side controller invoking multiple resources for markup can get messy and be difficult to manage. As a result, it is usually best to forward to a single server-side artifact and have it generate markup for the client, and simply accept the fact that the generation of client-side markup has completed.