12 March 2009

Web applications: the difference between Forward and Redirecting?

As a web developer it's important to understand the basics of the HTTP request /response model and how web containers function around this. The difference between Forwarding and Redirecting is a fine example.

When programming your web application you need to know when to use Forward (which is most of the time tbh) and Redirect. In the past redirect was neglected due it's performance, however in today's MVC web app's it can be very useful when using the Redirect-after-Post pattern (or whatever you want to call it).

Explained, in summary, Java been the language of choice:

The Request / Response flow of a Forward

1) Client makes a GET/POST request for a URL '/ForwardAction.action'
2) Server resolves URL and calls Servlet's doGet / doPost method
3) Server calls RequestDispatcher and Forwards to another URL e.g. 'forward.jsp' and sends the response
4) Client recieves the HTTP 200 response completely unaware of the internally forwarding,
the orginal 'ForwardAction.action' URL remains.

The Request / Response of a Redirect

1) Client makes a GET/POST request for a URL '/RedirectAction.action'
2) Server calls sendRedirect with the URL to redirect to e.g. 'redirect.jsp'
3) A 307 HTTP response is sent to the client with 'redirect.jsp' in the location
4) Client makes a GET request to 'redirect.jsp'. A fresh request.

The differences have implications to the state management of your web app, i.e. all request attributes are lost on step 4) of a redirect whereas they are still present in step 4) of a Forward.

No comments:

Post a Comment