Include vs. Forward of the Servlet RequestDispatcher

Java servlets

Include vs. Forward of the Servlet RequestDispatcher

By Matthew Stewart

TheServerSide.com

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.

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.

02 Oct 2011

Related Content

Related Resources

Disclaimer: Our Tips Exchange is a forum for you to share technical advice and expertise with your peers and to learn from other enterprise IT professionals. TechTarget provides the infrastructure to facilitate this sharing of information. However, we cannot guarantee the accuracy or validity of the material submitted. You agree that your use of the Ask The Expert services and your reliance on any questions, answers, information or other materials received through this Web site is at your own risk.