22_3 Spring MVC - ViewResolver系列 - XmlViewResolver
22_3 Spring MVC - ViewResolver系列 - XmlViewResolver
一、简介
XmlViewResolver是XML视图解析器,它实现了ViewResolver接口,接收相同DTD定义的xml配置文件定义的视图Bean对象。
二、源码解析
在XmlViewResolver 直接实现了 抽象方法 loadView来完成View的创建
2.1 loadView
@Override
protected View loadView(String viewName, Locale locale) throws BeansException {
BeanFactory factory = initFactory();
try {
return factory.getBean(viewName, View.class);
}
catch (NoSuchBeanDefinitionException ex) {
// Allow for ViewResolver chaining...
return null;
}
}
- 先通过 initFactory 初始化Spring容器
- 然后使用创建的Spring容器根据 视图名称创建一个View并返回
2.2 initFactory()
public static final String DEFAULT_LOCATION = "/WEB-INF/views.xml";
protected synchronized BeanFactory initFactory() throws BeansException {
if (this.cachedFactory != null) {
return this.cachedFactory;
}
ApplicationContext applicationContext = obtainApplicationContext();
Resource actualLocation = this.location;
// 如果不指定XmlViewResolver的配置文件,则使用默认的
if (actualLocation == null) {
actualLocation = applicationContext.getResource(DEFAULT_LOCATION);
}
// Create child ApplicationContext for views.
GenericWebApplicationContext factory = new GenericWebApplicationContext();
factory.setParent(applicationContext);
factory.setServletContext(getServletContext());
// Load XML resource with context-aware entity resolver.
XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(factory);
reader.setEnvironment(applicationContext.getEnvironment());
reader.setEntityResolver(new ResourceEntityResolver(applicationContext));
reader.loadBeanDefinitions(actualLocation);
factory.refresh();
if (isCache()) {
this.cachedFactory = factory;
}
return factory;
}
- 创建 XmlBeanDefinitionReader 对象
- 通过 reader.loadBeanDefinitions(actualLocation); 方法加载xml配置文件
- 可以看到如果不指定XmlViewResolver的配置文件,那么默认配置文件是
/WEB-INF/views.xml
这个文件
三、使用方法
3.1 配置视图解析器
<bean id="viewResolver" class="org.springframework.web.servlet.view.XmlViewResolver">
<property name="location" value="/WEB-INF/views.xml"></property>
</bean>
3.2 配置视图配置文件views.xml里各项的配置
<bean id="parent-view" class="org.springframework.web.servlet.view.JstlView">
<property name="attributes">
<props> <prop key="title">FlightDeals.com</prop> <prop key="season">Summer</prop>
</props>
</property>
<property name="url" value="/index.jsp"></property>
</bean>
<bean id="home" parent="parent-view">
<property name="url" value="/WEB-INF/jsp/home.jsp"/>
</bean>
<bean id="listFlight" parent="parent-view">
<property name="url" value="/WEB-INF/jsp/listFlights.jsp"/>
</bean>
- 当Controller返回的视图名是 home或者 listFlight时,根据定义的id寻找匹配的View这里是JstlView
- 按照匹配的url的属性值,使用JstlView去解析属性值进行视图的解析,将最终的视图页面展示给用户
知行合一