RequestDispatcher.forward() vs HttpServletResponse

2018-12-31 05:37发布

What is the conceptual difference between forward() and sendRedirect()?

8条回答
人气声优
2楼-- · 2018-12-31 06:06

requestDispatcher - forward() method

  1. When we use forward method, request is transfer to other resource within the same server for further processing.

  2. In case of forward, web container handle all process internally and client or browser is not involved.

  3. When forward is called on requestdispatcher object we pass request and response objects so our old request object is present on new resource which is going to process our request.

  4. Visually we are not able to see the forwarded address, it is transparent.

  5. Using forward () method is faster than send redirect.

  6. When we redirect using forward and we want to use same data in new resource we can use request.setAttribute () as we have request object available.

SendRedirect

  1. In case of sendRedirect, request is transfer to another resource to different domain or different server for further processing.

  2. When you use sendRedirect, container transfers the request to client or browser so URL given inside the sendRedirect method is visible as a new request to the client.

  3. In case of sendRedirect call, old request and response objects are lost because it’s treated as new request by the browser.

  4. In address bar, we are able to see the new redirected address. It’s not transparent.

  5. sendRedirect is slower because one extra round trip is required, because completely new request is created and old request object is lost. Two browser request required.

  6. But in sendRedirect, if we want to use we have to store the data in session or pass along with the URL.

Which one is good?

Its depends upon the scenario that which method is more useful.

If you want control is transfer to new server or context and it is treated as completely new task then we go for Send Redirect. Generally, forward should be used if the operation can be safely repeated upon a browser reload of the web page will not affect the result.

Source

查看更多
若你有天会懂
3楼-- · 2018-12-31 06:06

The RequestDispatcher interface allows you to do a server side forward/include whereas sendRedirect() does a client side redirect. In a client side redirect, the server will send back an HTTP status code of 302 (temporary redirect) which causes the web browser to issue a brand new HTTP GET request for the content at the redirected location. In contrast, when using the RequestDispatcher interface, the include/forward to the new resource is handled entirely on the server side.

查看更多
与君花间醉酒
4楼-- · 2018-12-31 06:09

Technically redirect should be used either if we need to transfer control to different domain or to achieve separation of task.

For example in the payment application we do the PaymentProcess first and then redirect to displayPaymentInfo. If the client refreshes the browser only the displayPaymentInfo will be done again and PaymentProcess will not be repeated. But if we use forward in this scenario, both PaymentProcess and displayPaymentInfo will be re-executed sequentially, which may result in incosistent data.

For other scenarios, forward is efficient to use since as it is faster than sendRedirect

查看更多
浅入江南
5楼-- · 2018-12-31 06:10

First of all, the term "redirect" is in web development world the action of sending the client an empty HTTP response with just a Location header with therein the new URL on which the client has to send a brand new GET request. So basically:

  • Client sends a HTTP request to some.jsp.
  • Server sends a HTTP response back with Location: other.jsp header
  • Client sends a HTTP request to other.jsp (this get reflected in browser address bar!)
  • Server sends a HTTP response back with content of other.jsp.

You can track it with the webbrowser's builtin/addon developer toolset. Press F12 in Chrome/IE9/Firebug and check the "Network" section to see it.

Exactly the above is achieved by sendRedirect("other.jsp"). The RequestDispatcher#forward() doesn't send a redirect. Instead, it uses the content of the target page as HTTP response.

  • Client sends a HTTP request to some.jsp.
  • Server sends a HTTP response back with content of other.jsp.

However as the original HTTP request was to some.jsp, the URL in browser address bar remains unchanged.


The RequestDispatcher is extremely useful in the MVC paradigm and/or when you want to hide JSP's from direct access. You can put JSP's in /WEB-INF folder and use a Servlet which controls, preprocesses and postprocesses the requests. The JSPs in /WEB-INF folder are not directly accessible by URL, but the Servlet can access them using RequestDispatcher#forward().

You can for example have a JSP file in /WEB-INF/login.jsp and a LoginServlet which is mapped on an url-pattern of /login. When you invoke http://example.com/context/login, then the servlet's doGet() will be invoked. You can do any preprocessing stuff in there and finally forward the request like:

request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response);

When you submit a form, you normally want to use POST:

<form action="login" method="post">

This way the servlet's doPost() will be invoked and you can do any postprocessing stuff in there (e.g. validation, business logic, login the user, etc).

If there are any errors, then you normally want to forward the request back to the same page and display the errors there next to the input fields and so on. You can use the RequestDispatcher for this.

If a POST is been successful, you normally want to redirect the request, so that the request won't be resubmitted when the user refreshes the request (e.g. pressing F5 or navigating back in history).

User user = userDAO.find(username, password);
if (user != null) {
    request.getSession().setAttribute("user", user); // Login user.
    response.sendRedirect("home"); // Redirects to http://example.com/context/home after succesful login.
} else {
    request.setAttribute("error", "Unknown login, please try again."); // Set error.
    request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response); // Forward to same page so that you can display error.
}

A redirect thus instructs the client to fire a new GET request on the given URL. Refreshing the request would then only refresh the redirected request and not the initial request. This will avoid "double submits" and confusion and bad user experience. This is also called the POST-Redirect-GET pattern.

查看更多
无色无味的生活
6楼-- · 2018-12-31 06:15

Either of these methods may be "better", i.e. more suitable, depending on what you want to do.

A server-side redirect is faster insofar as you get the data from a different page without making a round trip to the browser. But the URL seen in the browser is still the original address, so you're creating a little inconsistency there.

A client-side redirect is more versatile insofar as it can send you to a completely different server, or change the protocol (e.g. from HTTP to HTTPS), or both. And the browser is aware of the new URL. But it takes an extra back-and-forth between server and client.

查看更多
弹指情弦暗扣
7楼-- · 2018-12-31 06:22

SendRedirect() will search the content between the servers. it is slow because it has to intimate the browser by sending the URL of the content. then browser will create a new request for the content within the same server or in another one.

RquestDispatcher is for searching the content within the server i think. its the server side process and it is faster compare to the SendRedirect() method. but the thing is that it will not intimate the browser in which server it is searching the required date or content, neither it will not ask the browser to change the URL in URL tab. so it causes little inconvenience to the user.

查看更多
登录 后发表回答