Expert Spring MVC and Web Flow

(Dana P.) #1

Because the Controllers are totally unaware of the view technology, it is easy to mix
and match the rendering toolkits and even use multiple toolkits concurrently in the same
application.


ModelAndView


When processing is complete, the Controlleris responsible for building up the collection of
objects that make up the response (the Model) as well as choosing what page (or View) the
user sees next. This combination of Model and Viewis encapsulated in a class named (drum
roll...) ModelAndView.
Spring MVC makes a special effort to keep the Controllerunaware of any view technolo-
gies used, helping to keep coupling low. Therefore, the Model is a Mapof arbitrary objects,
and the Viewis typically specified with a logical name. The view’s name is later resolved to an
actual Viewinstance, later in the processing pipeline. It is the View’s responsibility to intelli-
gently display and render the objects in the Model.


Building the Home Page Use Case


With the very basics of Spring MVC components introduced, we will now implement the first
use case. Because this is the first use case we are building, we will also set up and configure the
web application.


Spring MVC Components


For Use case #1, we need to build a home page that displays special deals for the user. These
special deals aren’t static—presumably they originate from a database—so a regular XHTML
page isn’t enough. Therefore, we will create a Controllerthat delegates to the service layer to
load up the special deals so that the Viewcan render them into XHTML.
The most basic Controllerimplementation is an org.springframework.web.servlet.mvc.
AbstractController, perfect for read-only pages and simple requests. It provides a simple call-
back for handling a request, along with facilities such as controlling caching via HTTP headers
and enforcing certain HTTP methods. For extremelysimple Controllers, you may implement
the Controllerinterface directly, although we don’t recommend it because AbstractController
provides many useful features applicable to all types of web requests.


■Tip The AbstractControlleris well suited for web resources that return dynamic information but don’t
respond to input.


Controller


Let’s begin by taking a look at the code, shown in Listing 4-8. We have created a Controller
named HomeController, to handle the dynamic home page of the application. The method to
notice is handleRequestInternal(), where the real work is performed.


CHAPTER 4 ■JUMP INTO SPRING MVC 53
Free download pdf