Wednesday, August 20, 2014

Forward vs Redirect

What happens when browser or any client asks for a resource at a location and the resource is actually sitting on a different location. Server can handle that situation primarily in two ways:
  • Forward
  • Redirect
Forward

In forward, server internally manages the change of location of the resource. If you see the picture below, the browser asks for resource at location 1 but the resource is sitting at 2. So the server internally forwards the request to location 2 and the resource is returned from 2.
Forward vs Redirect
Forward vs Redirect

Redirect

In case of redirect, the server when asked for resource at location 1, returns with a message to browser telling that the resource is actually sitting at location 2. Then the browser goes at location 2 and fetches the resource. The redirection are of two types
  • Temporary (HTTP status 302) : This means that the new location is just a temporary location and the resource will be back at location 1. This is useful when the main domain is under maintenance. 
  • Permanent (HTTP status 301): This is permanent redirection. It is an indication to the browser or the user client that the location of the resource has been permanently moved to new location. It is also an indication to search engines that the resource is now sitting at new location. This is an important aspect for SEO when the domains are relocated.

How we can do Forward and Redirect in different technologies

Javascript
Javascript is a browser component so there is not concept of forward. For redirection you can use the following code

<script type="text/javascript">
<!--
window.location = "Redirected URL here"
//-->
</script>

Java

In Java on server side we can do the forward and redirect as follows:

  • Forward: It's called on request dispatcher object
   RequestDispatcher rd=
       request.getRequestDispatcher("Location to Forward");
   rd.forward(request, response);
  • Redirect: It's called on response object
     response.sendRedirect("Location to Redirect");

No comments:

Post a Comment