Before explaining the difference between include,forward and sendRedirect a small information on the request and response objects which is created by
servlet container.
Whenever there is request from the client (i.e is browser eg: Internet explorer,safari,netscape etc., ) to the server, the servlet container creates two objects
1. request 2. response these objects are created by servlet container.
Now coming to our differences:-
all the three are used for inter servlet communication in different ways.
Forward :
Consider there are 2 servlets, servlet1 and servlet2, and now you are calling the servlet2 from servlet1, as we already discuss every servlet will be having request,response objects. servlet1 contains request,response objects and here the same objects will be forwarded to servlet2, with out knowledge of the
container request will be forwarded to servlet2, and in this case for 2 servlets only one request and repsone objects will be there.
Cautions : Forward need to be call before response is committed to the client otherwise you will end up with an exception.
Limitations : You can't forward the request outside of the context so the request should with in your site.
Advantages : performance wise it will be bit faster as second call is made with out knowledge of the container and there will not be a round trip to the client to server.
sendRedirect : Here also consider same example servlet1 and servlet2 and now if you want to call servlet2 from servlet1,
in this case the request and response of the servlet1 will be discarded and you will be redirected to the client, once again
the new request will be made from client for servlet2 and container will create new req,and resp objects for servlet2.
If you see here in this scenario, 2 request and 2 response objects are created by the container even though first request,response objects
are discarded container will create total 4 objects (2 req, 2resp) and there is a round trip to the server.
Advantages: You can access the servlet which is out side of the context also, so you can make a call to the servlet which is there in the other web site.
Limitations: There is a round trip performance wise bit slow and as there is no req,ans resp objects of servlet1 you can't get the values of ser1 and ser2.
Include : Include and forward are almost similar the only difference is, in include the servlet2 will be embedded in servlet1
and literally there will be only servlet will be there as it includes the the servlet2, where as in forward it will invoke the second
servlet dynamically so it won't embed the servlet2 in servlet1.
and one more major diff is as the include will embed the contents into servlet2 no need to take care of response committed to client.
I know the post bit lengthy the reason is i tried to explain everything clearly.