In this section, you will learn about resolving view through ViewResolver interface.In this section, you will learn about resolving view through ViewResolver interface.
In this section, you will learn about resolving view through ViewResolver interface.
In Spring, two Interfaces View and ViewResolver plays a very important role in handling views. The ViewResolver provides mapping between view and actual views. The request preparation is handled by the View Interface and it also passes the request to one of the view technologies.
Spring Web MVC controllers resolves logical view name either explicitly (e.g., by returning a String, View, or ModelAndView) or implicitly (i.e., based on conventions). In Spring, 'logical view name' represents Views and it is resolved by a view resolver. There are a few view resolver in Spring. Given below the list of view resolvers in Spring :
|AbstractCachingViewResolver||This view resolver caches views.|
|XmlViewResolver||This view resolver uses configuration file written in XML for view resolution.|
|ResourceBundleViewResolver||This view resolver uses ResourceBundle , represented by the bundle base name, to resolve view. Generally bundle is defined in a properties file, situated in the classpath.|
|UrlBasedViewResolver||This view resolver uses 'logical view name' returned to find the actual view.|
|InternalResourceViewResolver||This view resolver is the subclass of UrlBasedViewResolver and also supports InternalResourceView(practically Servlets and JSPs) and also subclasses such as JstlView and TilesView.|
|VelocityViewResolver / FreeMarkerViewResolver||This view resolver is the subclass of UrlBasedViewResolver which supports VelocityView, FreeMarkerView and its custom subclasses.|
|ContentNegotiatingViewResolver||This view resolver is the implementation of the ViewResolver interface which resolves view on the basis of request file name or Accept header.|
Configuration for UrlBasedViewResolver :
<bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/> <property name="prefix" value="/WEB-INF/jsp/"/> <property name="suffix" value=".jsp"/> </bean>
The view resolver adds the prefix and suffix to the returned "logical view name" to find the actual view. For example, if loginpage is returned then the actual view will be /WEB-INF/jsp/loginpage.jsp.
Configuration for ResourceBundleViewResolver :
<bean id="viewResolver" class="org.springframework.web.servlet.view.ResourceBundleViewResolver"> <property name="basename" value="views"/> <property name="defaultParentView" value="parentView"/> </bean>
The ResourceBundle represented by the basename is inspected by the ResourceBundleViewResolver to resolve view and each view it is supposed to resolve, it uses the value of the property [viewname].(class) as the view class and the value of the property [viewname].url as the view url.