What is the difference between response.sendRedirect() and request.getRequestDispatcher().forward(request,response)

Viewed 171192

I have got a problem with my page jump when I use JAVA, if I use:

response.sendRedirect("login.jsp")

then I get this url: http://localhost:8080/login.jsp

But if I use

request.getRequestDispathcer("login.jsp").forward(request, response)

then I get this url: http://localhost:8080/Shopping/login.jsp (the "Shopping" is the name of my module).

What's the difference?

5 Answers

To simply explain the difference,

  response.sendRedirect("login.jsp");

doesn't prepend the contextpath (refers to the application/module in which the servlet is bundled)

but, whereas

 request.getRequestDispathcer("login.jsp").forward(request, response);

will prepend the contextpath of the respective application

Furthermore, Redirect request is used to redirect to resources to different servers or domains. This transfer of control task is delegated to the browser by the container. That is, the redirect sends a header back to the browser / client. This header contains the resource url to be redirected by the browser. Then the browser initiates a new request to the given url.

Forward request is used to forward to resources available within the server from where the call is made. This transfer of control is done by the container internally and browser / client is not involved.

1.redirect return the request to the browser from server,then resend the request to the server from browser.

2.forward send the request to another servlet (servlet to servlet).

Redirect and Request dispatcher are two different methods to move form one page to another. if we are using redirect to a new page actually a new request is happening from the client side itself to the new page. so we can see the change in the URL. Since redirection is a new request the old request values are not available here.

Related