Spring MVC View Resolver Example
In this example we shall talk about Spring MVC View Resolvers. View Resolvers are usually provided by all MVC Frameworks, so that models can be rendered in a browser, without being tied to a specific view technology. Spring MVC Framework provides the ViewResolver
interface, that maps view names to actual views.
It also provides the View
interface, which addresses the request of a view to the view technology. So when a ModelAndView
instance is returned by a Controller, the view resolver will resolve the view according to the view name.
Below, we will discuss about three important View Resolver implementations provided by Spring MVC, InternalResourceViewResolver
, XmlViewResolver
and ResourceBundleViewResolver
. We will also see how we can make use of them all together.
You may skip project creation and jump directly to the beginning of the example below.
Our preferred development environment is Eclipse. We are using Eclipse Juno (4.2) version, along with Maven Integration plugin version 3.1.0. You can download Eclipse from here and Maven Plugin for Eclipse from here. The installation of Maven plugin for Eclipse is out of the scope of this tutorial and will not be discussed. We are also using JDK 7_u_21. Tomcat 7 is the application server used.
Let’s begin:
1. Create a new Maven project
Go to File -> Project ->Maven -> Maven Project.
In the “Select project name and location” page of the wizard, make sure that “Create a simple project (skip archetype selection)” option is unchecked, hit “Next” to continue with default values.
Here the maven archetype for creating a web application must be added. Click on “Add Archetype” and add the archetype. Set the “Archetype Group Id” variable to "org.apache.maven.archetypes"
, the “Archetype artifact Id” variable to "maven-archetype-webapp"
and the “Archetype Version” to "1.0"
. Click on “OK” to continue.
In the “Enter an artifact id” page of the wizard, you can define the name and main package of your project. Set the “Group Id” variable to "com.javacodegeeks.snippets.enterprise"
and the “Artifact Id” variable to "springexample"
. The aforementioned selections compose the main project package as "com.javacodegeeks.snippets.enterprise.springexample"
and the project name as "springexample"
. Set the “Package” variable to "war"
, so that a war file will be created to be deployed to tomcat server. Hit “Finish” to exit the wizard and to create your project.
The Maven project structure is shown below:
- /src/main/java folder, that contains source files for the dynamic content of the application,
- /src/test/java folder contains all source files for unit tests,
- /src/main/resources folder contains configurations files,
- /target folder contains the compiled and packaged deliverables,
- /src/main/resources/webapp/WEB-INF folder contains the deployment descriptors for the Web application ,
- the pom.xml is the project object model (POM) file. The single file that contains all project related configuration.
2. Add Spring-MVC dependencies
Add the dependencies in Maven’s pom.xml
file, by editing it at the “Pom.xml” page of the POM editor. The dependency needed for MVC is the spring-webmvc
package, as shown below:
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.javacodegeeks.snippets.enterprise</groupId> <artifactId>springexample</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>springexample Maven Webapp</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> </dependency> </dependencies> <build> <finalName>springexample</finalName> </build> <properties> <spring.version>3.2.3.RELEASE</spring.version> </properties> </project>
3. Configure the application
The files that we must configure in the application are the web.xml
file and the mvc-dispatcher-servlet.xml
file.
The web.xml
file is the file that defines everything about the application that a server needs to know. It is placed in the /WEB-INF/
directory of the application. The <servlet>
element declares the DispatcherServlet
. When the DispatcherServlet
is initialized, the framework will try to load the application context from a file named [servlet-name]-servlet.xml
located in /WEB-INF/
directory. So, we have created the mvc-dispatcher-servlet.xml
file, that will be explained below. The <servlet-mapping>
element of web.xml
file specifies what URLs will be handled by the DispatcherServlet
.
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>Archetype Created Web Application</display-name> <servlet> <servlet-name>mvc-dispatcher</servlet-name> <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>mvc-dispatcher</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
The mvc-dispatcher-servlet.xml
file is also placed in WebContent/WEB-INF
directory. This is the file where all beans created, such as Controllers, will be placed and defined. So, the HelloWorldController
, that is the controller of our application is defined here, and will be shown in next steps. The <context:component-scan>
tag is used so that the container will know where to search for the classes.
mvc-dispatcher-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"> <context:component-scan base-package="com.javacodegeeks.snippets.enterprise" /> <bean class="com.javacodegeeks.snippets.enterprise.HelloWorldController" /> <bean </beans>
4. Create the View
The view is a simple jsp
page, placed in /WEB-INF/
folder. It shows the value of the attribute that was set to the Controller
.
helloWorld.jsp
<html> <body> <h1>Spring 3.2.3 MVC view resolvers example</h1> <h3> ${msg}</h3> </body> </html>
5. Create the Controller
The HelloWorldController
extends the AbstractController
provided by Spring, and overrides the handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
method, where a org.springframework.web.servlet.ModelAndView
is created by a handler and returned to be resolved by the DispatcherServlet
.
HelloWorldController.java
package com.javacodegeeks.snippets.enterprise; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.AbstractController; public class HelloWorldController extends AbstractController{ @Override protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { ModelAndView model = new ModelAndView("helloWorld"); model.addObject("msg", "hello world!"); return model; } }
6. InternalResourceViewResolver
The InternalResourceViewResolver
maps the jsp
and html
files in the WebContent/WEB-INF/
folder. It allows us to set properties such as prefix
or suffix
to the view name to generate the final view page URL. It is configured as shown below in mvc-dispatcher-servlet.xml
.
mvc-dispatcher-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"> <context:component-scan base-package="com.javacodegeeks.snippets.enterprise" /> <bean class="com.javacodegeeks.snippets.enterprise.HelloWorldController" /> <bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping" /> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix"> <value>/WEB-INF/</value> </property> <property name="suffix"> <value>.jsp</value> </property> </bean> </beans>
When the Controller returns the "helloworld"
view, the InternalResourceViewResolver
will create the url of the view making use of the prefix
and suffix
properties that are set to it, and will map the "helloworld"
view name to the correct "helloworld"
view.
7. XmlViewResolver
XmlViewResolver
is an implementation of ViewResolver
that accepts a configuration file written in XML, where the view implementation and the url
of the jsp
file are set. Below is the configuration file, views.xml
.
views.xml
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id="helloWorld" class="org.springframework.web.servlet.view.JstlView"> <property name="url" value="/WEB-INF/helloWorld.jsp" /> </bean> </beans>
The resolver is defined in mvc-dispatcher-servlet.xml
. It provides a property to configure, which is the location
property, and there the path of the configuration file is set.
mvc-dispatcher-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"> <context:component-scan base-package="com.javacodegeeks.snippets.enterprise" /> <bean class="com.javacodegeeks.snippets.enterprise.HelloWorldController" /> <bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping" /> <bean class="org.springframework.web.servlet.view.XmlViewResolver"> <property name="location"> <value>/WEB-INF/views.xml</value> </property> </bean> </beans>
Now, when the Controller returns the "helloworld"
view, the XmlViewResolver
will make use of the views.xml
file to get the view class and the url
of the view that will be mapped to the name "helloworld"
.
8. ResourceBundleViewResolver
The ResourceBundleViewResolver
uses bean definitions in a ResourceBundle
, that is specified by the bundle basename
. The bundle is typically defined in a properties file, located in the classpath. Below is the views.properties
file.
views.properties
helloworld.(class)=org.springframework.web.servlet.view.JstlView helloworld.url=/WEB-INF/helloworld.jsp
The ResourceBundleViewResolver
is defined in mvc-dispatcher-servlet.xml
, and in its definition the basename
property is set to view.properties
file.
mvc-dispatcher-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"> <context:component-scan base-package="com.javacodegeeks.snippets.enterprise" /> <bean class="com.javacodegeeks.snippets.enterprise.HelloWorldController" /> <bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping" /> <bean class="org.springframework.web.servlet.view.ResourceBundleViewResolver"> <property name="basename" value="views" /> </bean> </beans>
So, in this case, when the Controller returns the "helloworld"
view, the ResourceBundleViewResolver
will make use of the views.properties
file to get the view class and the url
of the view that will be mapped to the name "helloworld"
.
9. Configure multiple View Resolvers together
In order to set multiple Resolvers together in the same configuration file, you can set the order
property in all definitions, so that the order that they are used will be defined, as shown below:
mvc-dispatcher-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"> <context:component-scan base-package="com.javacodegeeks.snippets.enterprise" /> <bean class="com.javacodegeeks.snippets.enterprise.HelloWorldController" /> <bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping" /> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix"> <value>/WEB-INF/</value> </property> <property name="suffix"> <value>.jsp</value> </property> <property name="order" value="2" /> </bean> <bean class="org.springframework.web.servlet.view.XmlViewResolver"> <property name="location"> <value>/WEB-INF/views.xml</value> </property> <property name="order" value="1" /> </bean> <bean class="org.springframework.web.servlet.view.ResourceBundleViewResolver"> <property name="basename" value="views" /> <property name="order" value="0" /> </bean> </beans>
Note that the InternalResourceViewResolver
has the lowest priority, because it can map any request to the correct view, so if set before other resolvers the other resolvers will never be used.
In any of the four steps above, you can run your application, using a tomcat server and the result will be the one below:
10. Download the Source Code
This was an example of Spring MVC View Resolvers.
You can download the full source code of this example here: Spring MVC View Resolver Example