Once you have added your static attributes to the Viewinstance, they are merged with
the dynamic attributes and simply become part of the model as far as the view is concerned.
If any of your dynamic model attributes have the same name as a static attribute, the
dynamically generated one will take precedence. This is good because it means that you can
define defaults as static attributes and then optionally have your Controllerlogic override
those defaults.
■CautionYour attributes must be keyed with Strings. If you use the setAttributesMap()method and
the Mapcontains non-Stringkeys, a runtime exception will be generated.
Obviously your applications aren’t going to create views programmatically too often.
Much more commonly, you will define the view instances in a configuration file and have
Spring create them for you. There are several different ways to do this, and before we dive in
and take a look at them, we need to look more closely at the relationship between Controller
and View, and to introduce the ViewResolver.
Views and Controllers: Happily Divorced
Spring Controllers specify the following method in their interface shown in Listing 7-5.
Listing 7-5.Controller Interface Method
ModelAndView handleRequest(HttpServletRequest request,
HttpServletResponse response) throws Exception;
The important detail here is the return value from the handleRequest()method. A
ModelAndViewobject is a simple holder enabling your Controllerto return two distinct types
of object to the caller. The model in question is usually a Mapcontaining keyed object values of
the prepared data set that the view will render. The view might either be an implementation
itself (of the Viewinterface) or a Stringholding a name that will later be resolved to an actual
Viewby a ViewResolver, which we’ll learn more about in the next section.
Let’s look at a sample Controllerimplementation that takes the first option (Listing 7-6).
Listing 7-6.Returning a View Instance
public void handleRequestHttpServletRequest request,
HttpServletResponse response) throws Exception {
Map model = new HashMap();
model.put("flights", getFlightList());
View view = new InternalResourceView("/WEB-INF/jsp/flightList.jsp");
return new ModelAndView(view, model);
}
In Listing 7-6, the Controlleris responsible for determining the actual view implementa-
tion and returns this object along with the model it has generated. Note that this code still
makes no assumptions about how that particular view will render the content, and you are
CHAPTER 7 ■THE VIEW LAYER 207