The difference between Forward and Redirect in Servlet

Categories: Java; Tagged with: ; @ July 1st, 2012 15:16

Redirect:

response.sendRedirect(“ServletLogin”); // User not login, redirect to the login page.

“redirect sets the response status to 302, and the new url in a Location header, and sends the response to the browser. Then the browser, according to the http specification, makes another request to the new url”

And you can forward to any URL.

image

Forward:

request.getServletContext().getRequestDispatcher(“/s/HelloWorld”).forward(request, response);

forward happens entirely on the server. The servlet container just forwards the same request to the target url, without the browser knowing about that. Hence you can use the same request attributes and the same request parameters when handling the new url. And the browser won’t know the url has changed (because it has happened entirely on the server)

So we can get the parameters in the target method:

request.getParameter(“userName”) // HelloWorld…doPost()..

Ref: http://stackoverflow.com/questions/6068891/difference-between-jsp-forward-and-redirect


this picture is from: http://lukejin.iteye.com/blog/586091



// Proudly powered by Apache, PHP, MySQL, WordPress, Bootstrap, etc,.