Expert Spring MVC and Web Flow

(Dana P.) #1
To turn on an InternalResourceViewResolver, simply define it as a bean in the spring-
servlet.xmlfile, as we have done in Listing 4-11. You must then configure this resolver with a
prefix and suffix to be used when generating the full path to the view resource. For instance,
all of the JSP files are in the /WEB-INF/jsp/directory, and they all have the file extension .jsp.
Therefore, with a view name of home, a prefix of /WEB-INF/jsp/, and a suffix equal to .jsp, the
full path to the view resource becomes /WEB-INF/jsp/home.jsp.

Listing 4-11.ViewResolver Addition to spring-servlet.xml

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

■Tip It is good practice to place all view pages, including JSP pages, inside or below the /WEB-INFdirec-
tory. This protects the pages from being retrieved independently of the Controllers that configure them.

Summary
Let’s recap what we have done so far. Focusing on the home page use case, we have created a
Controllernamed HomeControllerand a JSP file for the view.
The HomeControllerdelegates to the FlightServiceto find any special deals and then
places those deals inside a ModelAndView. This ModelAndViewobject is returned from the
Controller, bringing along with it the name of the view to render.
The view name is resolved to a JSP file by an InternalResourceViewResolver, which creates
a full resource path by combing a prefix, the view name, and a suffix.
The InternalResourceViewResolverand HomeControllerare defined and configured in the
spring-servlet.xml file, which defines all the beans that make up the web components appli-
cation context.
With the web layer components complete we will now configure the web.xmlfile to initial-
ize the Spring MVC environment.

Web Application Configuration


The configuration of the web.xmlfile is quite simple for a Spring MVC application. Most of the
actual configuration is done via Spring’s bean definition XML files, so we will use the web.xml
to bootstrap our application and to define the central entry point.

Initializing the Root ApplicationContext
Spring MVC applications usually have two ApplicationContexts configured in a parent-child
relationship. The parent context, or root ApplicationContext, contains all of the non–web-
specific beans such as the services, DAOs, and supporting POJOs. For our example, the root

58 CHAPTER 4 ■JUMP INTO SPRING MVC

Free download pdf