In Spring MVC based application, the last step of request processing is to return the logical view name. Here DispatcherServlet has to delegate control to a view template so the information is rendered. This view template decides that which view should be rendered based on returned logical view name. These view templates are one or more view resolver beans declared in the web application context. These beans have to implement the ViewResolver interface for DispatcherServlet to auto-detect them. Spring MVC comes with several ViewResolver implementations. In this example, we will look at such a view resolver template i.e. XmlViewResolver.
Contrary to InternalResourceViewResolver where each logical view name is mapped to physical location of view directly, in case of
XmlViewResolver, views are declared as Spring beans. You can declare the view beans in the same configuration file as the web application context, but it’s better to isolate them in a separate configuration file.
XmlViewResolver loads view beans from
/WEB-INF/views.xml, but this location can be overridden through the location property.
<bean class="org.springframework.web.servlet.view.XmlViewResolver"> <property name="location"> <value>/WEB-INF/admin-views.xml</value> </property> </bean>
admin-views.xml configuration file, you can declare each view as a normal Spring bean by setting the class name and properties. e.g.
<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="home" class="org.springframework.web.servlet.view.JstlView"> <property name="url" value="/WEB-INF/jsp/home.jsp" /> </bean> <bean id="admin/home" class="org.springframework.web.servlet.view.JstlView"> <property name="url" value="/WEB-INF/jsp/admin/home.jsp" /> </bean> <bean id="logOffRedirect" class="org.springframework.web.servlet.view.RedirectView"> <property name="url" value="home" /> </bean> </beans>
The first two beans in above configuration are pretty obvious. Logical view name “home” is mapped to “/WEB-INF/jsp/home.jsp” and “admin/home” is mapped to “/WEB-INF/jsp/admin/home.jsp“.
The third bean do not map any physical view file, rather it redirect the request to url “home” which is actually handled by controller of URL “/home“. Whatever logical name that controller will return, that view will be looked up into bean mappings and then actual view file will be obtained.
Drop me your queries if something needs more explanation.
Happy Learning !!
All of my websites are hosted on Bluehost. Why? Because they make it incredibly easy to get a new site up and running with their one-click automatic WordPress Blog installation.
You can use your Bluehost account to host multiple domains—no need to pay more for hosting when you’re ready to start another website.