What is the difference between jsp:forward and response.sendRedirect?

There's an important difference between a forward and a redirect. The <jsp:forward ..> is actually a call to HttpServletRequest.forward(String url) which passes the request object within the server to either a servlet or a JSP page. The new servlet or JSP page continues to process the same request and the browser is not aware of the fact that more than one servlet or page is involved. In other words, the client is not aware that the request is being forwarded anywhere. The URL shown in the browser stays unchanged when you do forward.

The <jsp:forward> element forwards the request object containing the client request information from one JSP file to another file. The target file can be an HTML file, another JSP file, or a servlet, as long as it is in the same application context as the forwarding JSP file. The lines in the source JSP file after the <jsp:forward> element are not processed.

The page invoked by the <jsp:forward> action has access to all the parameters in the original request object. You can add new parameters to the request object to pass to the target page by using the <jsp:param name="..." value="..." />.

Be careful when using <jsp:forward> with unbuffered output. If the JSP file has any data in the out object, using will cause an IllegalStateException.

The response.sendRedirect() creates a new request object which doesn't carry any of old requests. The first request handler JSP page tells the browser to make a new request to the target servlet or JSP page. The URL shown in the browser therefore changes to the URL of the new page when you redirect.

A redirect is slower than a forward because the browser has to make a new request. Another difference is that request scope objects are no longer available after a redirect because it results in a new request. If you need to pass data to the page you redirect to, you have to use a query string and pass them as request parameters (or save the data as session or application scope objects).

Forward is faster than redirect but one disadvantage is that URL is not changed and also it works with in same web application. Also, when you choice to use forward, you need to ask what happens if the user reloads the page.

Printer-friendly version Printer-friendly version | Send this 
article to a friend Mail this to a friend

Previous Next vertical dots separating previous/next from contents/index/pdf Contents

  |   |