概述
Spring MVC
的一个概念模型接口,用于完成功能从视图名称获取相应的视图对象,故名View Resolver
(“视图解析器”)。本接口只定义了一个方法:
View resolveViewName(String viewName, Locale locale) throws Exception;
该方法根据视图名称和指定的Locale
本地化信息获取相应的View
对象,如果解析不到指定名称的视图,则返回null
。Spring MVC
约定整个应用运行期间,视图的状态不发生变化,所以各个ViewResolver
可以对所解析到的View
做缓存。
对整个应用而言,Spring MVC
可以同时使用多个ViewResolver
,一个ViewResolver
返回null
并不表示指定的视图不存在,而是有可能会被下一个ViewResolver
解析得到。
Spring MVC
应用启动时,框架某个部分或者开发人员定义的ViewResolver
组件会被注册到容器。然后DispatcherServlet
初始化时初始化方法initViewResolvers
会搜集到这些ViewResolver
组件并记录到自己的属性List<ViewResolver> viewResolvers
。随后DispatcherServlet
处理请求解析视图时就会用到这些ViewResolver
。
举例来讲,对于一个使用Spring Boot + Spring MVC + Freemarker
的应用来讲,缺省使用如下ViewResolver
组件:
ContentNegotiatingViewResolver viewResolver
由
WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter
定义。BeanNameViewResolver beanNameViewResolver
由
WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter
定义。FreeMarkerViewResolver freeMarkerViewResolver
由
FreeMarkerAutoConfiguration
/FreeMarkerServletWebConfiguration
定义。ViewResolverComposite mvcViewResolver
由
WebMvcAutoConfiguration$EnableWebMvcConfiguration
(继承自WebMvcConfigurationSupport
)定义。InternalResourceViewResolver defaultViewResolver
由
WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter
定义。
源代码
源代码版本 : spring-webmvc-5.1.5.RELEASE
package org.springframework.web.servlet;
import java.util.Locale;
import org.springframework.lang.Nullable;
/**
* Interface to be implemented by objects that can resolve views by name.
*
* View state doesn't change during the running of the application,
* so implementations are free to cache views.
*
* Implementations are encouraged to support internationalization,
* i.e. localized view resolution.
*
* @author Rod Johnson
* @author Juergen Hoeller
* @see org.springframework.web.servlet.view.InternalResourceViewResolver
* @see org.springframework.web.servlet.view.ResourceBundleViewResolver
* @see org.springframework.web.servlet.view.XmlViewResolver
*/
public interface ViewResolver {
/**
* Resolve the given view by name.
* Note: To allow for ViewResolver chaining, a ViewResolver should
* return null if a view with the given name is not defined in it.
* However, this is not required: Some ViewResolvers will always attempt
* to build View objects with the given name, unable to return null
* (rather throwing an exception when View creation failed).
* @param viewName name of the view to resolve
* @param locale the Locale in which to resolve the view.
* ViewResolvers that support internationalization should respect this.
* @return the View object, or null if not found
* (optional, to allow for ViewResolver chaining)
* @throws Exception if the view cannot be resolved
* (typically in case of problems creating an actual View object)
*/
@Nullable
View resolveViewName(String viewName, Locale locale) throws Exception;
}