Include vs. Forward of the Servlet 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.

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.

This was first published in October 2011

0 comments

Oldest 

Forgot Password?

No problem! Submit your e-mail address below. We'll send you an email containing your password.

Your password has been sent to:

-ADS BY GOOGLE

SearchCloudApplications

SearchSOA

SearchSoftwareQuality

SearchFinancialApplications

SearchSAP

SearchManufacturingERP

Close