A Word on Redirecting
■NoteThis section is naturally about views, but we’ve left it until after the discussion on ViewResolvers
because we need a degree of knowledge about resolvers before tackling RedirectViews fully.
Sometimes you don’t want a view to be rendered as part of a single request-response transac-
tion from the client. This usually applies to form data that is POSTed to a Controllerwhere
the correct response might be to delegate to another Controller. When you do this internally,
the delegate Controllerhas access to all of the form POST data, which may not be desirable.
In addition, the user can double-post the form data by reloading the current page in the
browser after submitting the form.
Both of these problems can be overcome by having the Controllerthat receives the form
POST issue a redirect to the client, shown in Figure 7-6. This causes the browser to make a
new request the URL in the address bar to change too. Now if the user hits the Reload button,
she’ll get the page that was the subject of the redirect and won’t inadvertently submit a new
set of form POST details—something that could involve a credit card purchase. The problem
and its “Redirect after POST” solution are commonly understood, so let’s take a look at how to
deal with this in Spring MVC applications.
Figure 7-6.Redirect after POST
Spring provides a RedirectViewclass—which implements the Viewinterface—but under
the covers simply sets the response headers to force the client to re-request its configured URL.
If you’re using ResourceBundleViewResolveror XmlViewResolver, you can define RedirectViews
as you would any other view. If, however, you’ve chosen to use an UrlBasedViewResolveror one
of its subclasses, then the nature of the resolver makes it impossible to specify a redirect simply
by using a logical key as the view name.
: client : DispatcherServlet : SimpleFormController: RedirectView successController : Controller successView : View
: [POST form data]
HTTP 302 / 303
: [GET successUrl]
: onSubmit(command : Object) : ModelAndView
: render()
response.sendRedirect() or response.setStatus(303)
: handleRequest() : ModelAndView
: render()
CHAPTER 7 ■THE VIEW LAYER 215