Monday, December 22, 2014

Difference between sendRedirect() vs forward()

sendRedirect()

response.sendRedirect();

sendRedirect can let the servlet to move on to a completely new Application Url

Need response object to call the method.

It takes the string url path as an Argument. The value may be a complete url path or a relative path

Created new request and response object to the redirected URL

Assume that the client originally typed in:
http://www.myworld.com/com/raj/info.do

When the request comes into the servlet named “info.do”, 
the servlet calls sendRedirect() with a relative URL that does NOT start with a forward slash:
sendRedirect(“personal/Information.html”); // NO SLASH AT THE BEGINNING

The Container builds the full URL (it needs this for the “Location” header it
puts in the HTTP response) relative to the original request URL:
http://www.myworld.com/com/raj/personal/Information.html

But if the argument to sendRedirect() DOES start with a forward slash:
sendRedirect(/personal/Information.html); // SLASH AT THE BEGINNING

The Container builds the complete URL relative to the web Container itself, instead
of relative to the original URL of the request. So the new URL will be:
http://www.myworld.com/personal/Information.html

sendRedirect() change the Url as per the usage of the string value in the argument

Browser created new request object to the redirected url

.forward()

RequestDispatcher view = request.getRequestDispatcher(“Process.jsp”);
view.forward(request,response);

Need RequestDispatcher object with the string Url value as an Argument

Need to pass request, response object into the forward method

Takes the same (existing) request and response object to the redirected URL

The Url is not getting changed in the browser location bar.

No comments:

Post a Comment

Scrum and Scrum master

Scrum  Scrum is a framework which helps a team to work together.  It is like a rugby team (the scrum name comes from rugby game). Scrum enco...