File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Servlets and the fly likes What's the different between Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Servlets
Bookmark "What Watch "What New topic

What's the different between "forward" and "include"?

Keane sh

Joined: Dec 13, 2001
Posts: 8
I use the requestdispatcher() method to dispatch a jsp page,but I find the result between "forward" and "include" is no diffence.
And I couldn't find out the result of its description in JDK's API.
Thank you for you!
David O'Meara

Joined: Mar 06, 2001
Posts: 13459

From the Servlet API:

Forwards a request from a servlet to another resource (servlet, JSP file, or HTML file) on the server. This method allows one servlet to do preliminary processing of a request and another resource to generate the response.
forward should be called before the response has been committed to the client (before response body output has been flushed). If the response already has been committed, this method throws an IllegalStateException. Uncommitted output in the response buffer is automatically cleared before the forward.

Includes the content of a resource (servlet, JSP page, HTML file) in the response. In essence, this method enables programmatic server-side includes.
The ServletResponse object has its path elements and parameters remain unchanged from the caller's. The included servlet cannot change the response status code or set headers; any attempt to make a change is ignored.

If you have a "response part" that returns nothing, then if you forward or include the next part then the results will be the same.
If you have a "response part" that sends a small amount of data (typically less than 8kb), if you forward then that data will be erased, if you include the results will be contatenated (added together)
If you have a "response part" that sends a large amount of data (greater than 8kb), if you forward an exception will be thrown since you are "committed" to this response, if you include then the results will be concatenated.
include allows you to build pages from multiple bits, eg including common headers and footers in multiple pages from the same source file.
forward allows you to process in one page then "throw off" to a separate page for presentation, where the presentation is completely separate to the processing that went before hand, like when using Model 2 (or MVC) architecture.
Keane sh

Joined: Dec 13, 2001
Posts: 8
Thank you , David.
Don't get me started about those stupid light bulbs.
subject: What's the different between "forward" and "include"?
It's not a secret anymore!