Forward Versus Redirect

It’s often necessary for more than one component to share control of a request. For example, one servlet may be responsible for authenticating and authorizing a client, while it’s the job of a different servlet to retrieve some data for the user. The sharing of a request can be accomplished in several different ways.

There are important differences between how a web container processes a forward request versus how it processes a redirect. The Struts front controller servlet, discussed in Chapter 1, will always perform one or the other for a typical request, so it’s important that you understand these differences and the impact that each mechanism will have on your application.

Using a Redirect

When the sendRedirect() method is invoked, it causes the web container to return to the browser a response indicating that a new URL should be requested. Because the browser issues a completely new request, any objects that are stored as request attributes before the redirect occurs will be lost. This is one of the biggest differences between a forward and redirect. Figure 2-5 illustrates why this occurs.

A redirect causes the browser to issue a new request

Figure 2-5. A redirect causes the browser to issue a new request

Because of the extra round trip that occurs, a redirect is slower than a forward. Example 2-1 provides an example servlet that performs a redirect for a JSP page called result.jsp when a request for the ...

Get Programming Jakarta Struts, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.