基础知识 forward与 Sendredirect

来源:互联网 发布:2017社交软件排行 编辑:程序博客网 时间:2024/05/21 19:47

its the most common question in the interviews..

Forward( ) : javax.Servlet.RequestDispatcher interface.
- RequestDispatcher.forward( ) works on the Server.
- The forward( ) works inside the WebContainer.
- The forward( ) restricts you to redirect only to a resource in the same web-Application.
- After executing the forward( ), the control will return back to the same method from where the forward method was called.
- The forward( ) will redirect in the application server itself, it does'n come back to the client.
- The forward( ) is faster than Sendredirect( ) .

To use the forward( ) of the requestDispatcher interface, the first thing to do is to obtainRequestDispatcher Object. The Servlet technology provides in three ways.

1. By using the getRequestDispatcher( ) of the javax.Servlet.ServletContext interface , passing aString containing the path of the other resources, path is relative to the root of theServletContext.
RequestDispatcher rd=request.getRequestDispatcher ("secondServlet");
Rd.forward(request, response);

2. getRequestDispatcher( ) of the javax.Servlet.Request interface , the path is relative to current HtpRequest.
RequestDispatcher rd=getServletContext( ).getRequestDispatcher("servlet/secondServlet");
Rd.forward(request, response);

3. By using the getNameDispatcher( ) of the javax.Servlet.ServletContext interface.
RequestDispatcher rd=getServletContext( ).getNameDispatcher("secondServlet");
Rd.forward(request, response);

Sendredirect( ) : javax.Servlet.Http.HttpServletResponce interface
- RequestDispatcher.SendRedirect( ) works on the browser.
- The SendRedirect( ) allows you to redirect trip to the Client.
- The SendRedirect( ) allows you to redirect to any URL.
- After executing the SendRedirect( ) the control will not return back to same method.
- The Client receives the Http response code 302 indicating that temporarly the client is being redirected to the specified location , if the specified location is relative , this method converts it into an absolute URL before redirecting.
- The SendRedirect( ) will come to the Client and go back,.. ie URL appending will happen.

Response. SendRedirect( "absolute path");
Absolutepath – other than application , relative path - same application.

When you invoke a forward request, the request is sent to another resource on the server, without the client being informed that a different resource is going to process the request. This process occurs completely with in the web container. When a sendRedirtect method is invoked, it causes the web container to return to the browser indicating that a new URL should be requested. Because the browser issues a completely new request any object that are stored as request attributes before the redirect occurs will be lost. This extra round trip a redirect is slower than forward.

原创粉丝点击