still at liberty to change the JSP—or even the implementation of InternalResourceView
without reference to any of the Controllers that use it.
The preceding code could be improved by having the Controllerlook the view up in an
ApplicationContext, but it doesn’t greatly improve upon the example from a design perspective.
The Controllerstill needs to have too much information about where to find a particular view.
A better alternative, shown in Listing 7-7, is to have the Controllerspecify a key that
names the view. Specifying a name for a view is crucial to how a web framework is able to
completely decouple the view from the Controller. A Controllercan effectively delegate the
choice of view to another object which knows how to find and instantiate a view based on an
abstract name. Constructing a ModelAndViewwith a view name rather than a Viewinstance is
much the more common approach in Spring MVC applications and in fact, almost all web
frameworks offer a mechanism of addressing views by name.
Listing 7-7.Returning a Named View
public void handleRequestHttpServletRequest request,
HttpServletResponse response) throws Exception {
Map model = new HashMap();
model.put("flights", getFlightList());
return new ModelAndView("flightList", model);
}
In the second example, your Controllerknows nothing of the view other than its name.
That’s good! You are now free to vary the typeof view that is actually used to render this model,
without revisiting even your Controllercode.
■CautionBe aware that the ModelAndViewconstructors are slightly counterintuitive, in that you specify
the view or view name first, followed by the model.
ViewResolvers
The key to a complete decoupling of the view from the Controlleris not to permit the
Controllerany say in what type of view will be used to render the model. So if the Controller
is now divorced from this responsibility, who or what isresponsible? This job falls to the
ViewResolver. ViewResolvers are an important feature in Spring’s view layer support.
When your Controllerselects a concrete view to return as part of the ModelAndViewobject, it
still knows nothing of howthat implementation will perform its job. However, it necessarily has
knowledge of whichview will perform the rendering task. In some scenarios this may be accept-
able, but in the general case it would be better for your Controllersnot to be burdened with this
additional responsibility.
This is where a ViewResolvercomes into play. Listing 7-8 has the definition for this interface.
208 CHAPTER 7 ■THE VIEW LAYER