Expert Spring MVC and Web Flow

(Dana P.) #1
Listing 8-1.Setting Up the InternalResourceViewResolver in the WebApplicationContext

<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.InternalResourceView"/>
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>

Listing 8-2.Specifying Model and View from the Home Controller

@Override
protected ModelAndView handleRequestInternal(
HttpServletRequest req, HttpServletResponse res)
throws Exception {
ModelAndView mav = new ModelAndView("home");
mav.addObject("specials", flights.getSpecialDeals());
return mav;
}

The Controllercode should be very familiar by now; it simply declares that a Viewwith
the logical name homeshould be used to handle the model. It doesn’t need to know or care that
a JSP will actually do that job for you. The model consists of a single object—the list of special
deals—keyed under the name specials.
The ViewResolverdefinition shown in Listing 8-1 has the interesting information—and is
where the magic occurs. First, we specify which Viewimplementation class will be used and we
specify a prefix and a suffix that will be (surprise) prefixed and suffixed to the logical name. So
when the resolver is asked to resolve a Viewname of homeby the DispatcherServlet, it returns an
object that wraps the JSP located at /WEB-INF/jsp/home.jsp—the physical location of your JSP
file in the web application.

Exposing the Model As Request Attributes


Clever stuff—and so far, so good—but what about our model? The home.jspwon’t be much use if
it doesn’t have access to the model attributes that our Controllerobtained from the service layer
of the application. This is where the render()method of the Viewinterface comes into play as it
is this method (or more commonly, a delegate method) that is responsible for knowing how to
make a generic model available to the specific view technology, in this case JSP.
InternalResourceViewmakes the model available to a JSP in the form of request attrib-
utes. An extract from the code in this class shown in Listing 8-3 demonstrates how.

Listing 8-3.Exposing the Model in InternalResourceView

protected void
exposeModelAsRequestAttributes(Map model, HttpServletRequest request)
throws Exception {

224 CHAPTER 8 ■SUPPORTED VIEW TYPES

Free download pdf