What is the difference between Servlet Redirect versus Servlet Forward in Java

Consider your company as the world wide web and in your company you have many departments. So when you as an employee(Servlet) get's a request to do something and you pass that on to the another person directly in your own department then its considered a request forward. But if you send the request back to where it came from asking them to reassign the work to another department or another person in your own department then its considered a Redirect. Now here is the technical jargons explaining the same with pros and cons.

Servlet redirect and servlet forward both are used to handle the request processing to some other URL/Servlet but there is a big difference between them how they work. The main difference is

Servlet redirect always sends a HTTP status code 303 to client along with the redirect URL. Client then sends a new request to the URL.Thus response.sendRedirect() takes one more round trip than forward where as servlet forward just forwards the request to another resource on the server and it does not take a full round trip that is why forward is some time referred as server side redirect.

The another difference is you can redirect the request to a URL on different site but you can not forward the request to a URL on different site.

Servlet forward will forward the existing request to another JSP or Servlet, so all the request parameters and attributes will be available to destination servlet. However with redirect, browser sends new request to specified URL, so old request parameters and attributes will not be available to destination resource.

Browser is completely unaware of servlet forward and hence the URL in browser address bar will remain unchanged. Where as the URL in browser address bar will change to new URL when servlet redirect is used.

Java servlet redirecting

Redirecting uses the "sendRedirect()" method of the response object, which is obtained from the current Servlet class. For example, the following code will redirect the response to another page called destination.jsp:

Java servlet forwarding

Forwarding uses the RequestDispatcher class which is obtained from the "getServletContext()" method of the Servlet. To forward, the method "forward()" from the "RequestDispatcher class is called. For example, the following code will forward the response to another page called result.jsp: