Expert Spring MVC and Web Flow

(Dana P.) #1
The Controllerin this example is using logical Viewnames to identify which views should be
rendered. This provides a nice decoupling between the controller and how the Views are actually
implemented. The DispatcherServletwill delegate these Viewnames to a ViewResolverto resolve
the actual Viewinstances. For our example, we will use an InternalResourceViewResolver. This
ViewResolver works well with JSP files and lets us hide the actual JSP files behind the /WEB-INF
directory to prohibit unauthorized client access.

■Tip You should place any restricted or otherwise hidden files inside the/WEB-INFdirectory of your web
application. That directory, and all of its subdirectories, is protected by the servlet container.

The ViewResolveris declared and configured with a prefix and suffix, used to create a fully
qualified filename for the view. This bean definition (Listing 6-44) will typically reside in the
spring-servlet.xmlfile with the rest of the controller definitions and other web-specific beans.

Listing 6-44.ViewResolver Configuration

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

With our example controller using a view name of newPerson, the ViewResolverin Listing
6-45 will attempt to locate the file /WEB-INF/jsp/newPerson.jsp.
We obviously haven’t mentioned Validators or what happens if there is a validation error.
Validation is a large topic, so we are postponing a full discussion about validation to Chapter 9.
To continue with this example, we now want to modify the code to restrict the choices of
favorite programming language. The predetermined choices must be loaded before the initial
page view; thus we will override the referenceData()method.
First, we will create the list of approved languages to pick a favorite from. For the example,
the List’s contents are static, so we will create a simple array to be shared among requests.
It is common to require objects from persistence to be returned by referenceData(). If
that information is static, for performance reasons, load the objects only once at startup. This
will save on pulling them from the database for every request. In this case, your controller may
implement InitializingBean, which is a Spring-specific interface indicating that the bean
requires initializing before servicing requests.

■Tip For more information about the InitializingBeaninterface, consult the book Pro Springor the
online documentation. An alternative to InitializingBeanis theinit-methodattribute in the XML bean
definition, which avoids the need to implement a framework interface.

160 CHAPTER 6 ■THE CONTROLLER MENAGERIE

Free download pdf