Expert Spring MVC and Web Flow

(Dana P.) #1
You can, of course, simply have your Controllercreate a new RedirectViewas part of the
ModelAndViewthat it returns, but as we’ve already seen, we don’t really want the Controller
making that decision. The preferred option is to chain two ViewResolversat this point. You
should specify an XmlViewResolveror ResourceBundleViewResolverto resolve views that need
to be RedirectViews, falling back to the UrlBasedViewResolversfor all other views.
If you really can’t face chaining ViewResolvers, then there is a third alternative—introduced
in version 1.1.2 of Spring—specifying a special prefix in the view name. Because a view name
can be injected into a Controller, this still absolves your controller from knowing that a redirect
is going to occur, and hence, you still have completely decoupled components. Listing 7-13
shows the concept.

Listing 7-13.Using the Redirect Prefix

// viewName should really be injected as a bean property value
String viewName = "redirect:successpage.html";
return new ModelAndView(viewName, model);

The actual URL is specified relative to the context root of the web application so that the
controller need not be aware of the name that the application was deployed under, although
this behavior can be modified in configuration if you really want it.

Themes


You can further enhance your view layer visually through the use of themes. Themes may not
be appropriate for all view types—PDF and Excel, for example—but the manner in which you
define and use them is consistent across other view types.
Themes are a collection of resources, usually stylesheets (CSS) and images that augment the
display of your web pages. Several different themes can coexist in your application together, and
a Spring-supplied ThemeResolverclass does the work of determining which one will be applied
in the views.
Let’s see an example for better clarity. Listing 7-14 shows the contents of a properties file
that specifies some theme keys. We’ve called this file winter.properties.

Listing 7-14.The Winter Theme Definition Properties File

style=/styles/winter.css
background=/images/snow.png
welcome.message=Brrrr! It's cold.

The keys in the theme definition are referred to in your view layer code. In JSP, for example,
this can be done with the <spring:theme>tag, as shown in Listing 7-15.

Listing 7-15.Theme Properties Referred to in a JSP

<taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<html>
<head>
<link rel="stylesheet"

216 CHAPTER 7 ■THE VIEW LAYER

Free download pdf