Skip to main content

What is the difference between RequestDispatcher's forward method and HttpServletResponse's sendRedirect method?

RequestDispatcher's forward(ServletRequest request, ServletResponse response)
 

The forward() method of RequestDispatcher will forward the ServletRequest and ServletResponse that it is passed to the path that was specified in getRequestDispatcher(String path). The response will not be sent back to the client and the web container (For example, Tomcat) internally redirects the request to the other JSP/Servlet. Remember , you can redirect only to a page within current servlet context. The client will not know about this change of resource on the server.

The forward works better when one resource(JSP/Servlet) must perform business logic and share the results with another resource(JSP/Servlet). Because the request and response are forwarded to another resource all request parameters are maintained and available for use. Forward request, happened on server side, is transparent to the client (browser). Therefor, no history of it will be stored on the client, so using the back and forward buttons will not work.

An example using forward:

protected void doGet(HttpServletRequest request, 
HttpServletResponse response)
throws ServletException, IOException {
RequestDispatcher rd = request.getRequestDispatcher("pathToResource");
rd.forward(request, response);
}

Also there are two flavours of RequestDispatcher:

  • You can get it from ServletContext .The pathname must begin with a "/" and is interpreted as relative to the current context root.
  • You can get it from ServletRequest. The pathname specified may be relative, although it cannot extend outside the current servlet context. If the path begins with a "/" it is interpreted as relative to the current context root.

HttpServletResponse's sendRedirect(String location) Method

The sendRedirect(String path) method of HttpServletResponse actually modifies response header and tells the browser (the client) that the requested page is relocated and header also contains the new location of the page. Then browser (the client) will send the request again to this new location. Thus your request gets redirected. It requires a round-trip communication with the client. You can redirect the request any where in the web using sendRedirect. Because a new request is being submitted, all previous parameters stored in the request will be unavailable. The client's history will be updated so the forward and back buttons will work. This method is useful for redirecting to pages on other servers and domains.

An example using sendRedirect:

protected void doGet(HttpServletRequest request, 
HttpServletResponse response)
throws ServletException, IOException {
response.sendRedirect("pathToResource");
}

Summary

You can use only relative URLs with forward(), while sendRedirect() works with absolute URLs. This poses its own problems, as if your page has relative links(to images etc), if you use forward, there is a good chance they they will end up as broken links. Hence, it will be better to use sendRedirect() whenever possible and use forward() only when required.

When forward is used we can pass data to the forwarded jsp/servlet using request.setAttribute() as the same request and response objects available the forwarded servlet/jsp. But using sendRedirect() we have to set the data in session or by appending the data to the URL that will be passed as argument to this method, because by calling this method a new request is created.

The forward() request is transparent to the user. It is done at server side and it is not visible to user.

The sendRedirect is not transparent to the user, if request is sendRedirect then its visible in your browser (redirect at client side).

The forward() method is faster than using sendRedirect as no network round trip to the server and back is required.


Comments

Popular posts from this blog

Java Health Center - Overview and Features

This video highlights the features available in Health Center. Health Center is a low-processor and memory usage diagnostic tool for monitoring the status of a running IBM Java Virtual Machine (JVM). Health Center provides live information and recommendations in each of the following areas: - Classes: information about classes being loaded - Environment: details of the configuration and system of the monitored application - Garbage Collection: information about the Java heap and pause times - Locking: information about contention on inflated locks - Profiling: sampling profile of Java methods including call paths

WebSphere MQ Interview Questions

What is MQ and what does it do? Ans. MQ stands for MESSAGE QUEUEING. WebSphere MQ allows application programs to use message queuing to participate in message-driven processing. Application programs can communicate across different platforms by using the appropriate message queuing software products. What is Message driven process? Ans . When messages arrive on a queue, they can automatically start an application using triggering. If necessary, the applications can be stopped when the message (or messages) have been processed. What are advantages of the MQ? Ans. 1. Integration. 2. Asynchrony 3. Assured Delivery 4. Scalability. How does it support the Integration? Ans. Because the MQ is independent of the Operating System you use i.e. it may be Windows, Solaris,AIX.It is independent of the protocol (i.e. TCP/IP, LU6.2, SNA, NetBIOS, UDP).It is not required that both the sender and receiver should be running on the same platform What is Asynchrony? Ans. With messag...

Java Garbage Collection

Explain Garbage collection mechanism in Java? Garbage collection is one of the most important features of Java. The purpose of garbage collection is to identify and discard objects that are no longer needed by a program so that their resources can be reclaimed and reused. A Java object is subject to garbage collection when it becomes unreachable to the program in which it is used. Garbage collection is also called automatic memory management as JVM automatically removes the unused variables/objects (value is null) from the memory. Every class inherits finalize() method from java.lang.Object, the finalize() method is called by garbage collector when it determines no more references to the object exists. In Java, it is good idea to explicitly assign null into a variable when no more in use. In Java on calling System.gc() and Runtime.gc(), JVM tries to recycle the unused objects, but there is no guarantee when all the objects will garbage collected. Garbage collection is an automatic pro...