22_5 Spring MVC - ViewResolver系列 - InternalResourceViewResolver
22_5 Spring MVC - ViewResolver系列 - InternalResourceViewResolver
一、简介
InternalResourceViewResolver是URLBasedViewResolver的子类,所以URLBasedViewResolver支持的特性它都支持。在实际应用中InternalResourceViewResolver也是使用的最广泛的一个视图解析器。InternalResourceViewResolver会把返回的视图名称都解析为InternalResourceView对象,InternalResourceView会把Controller处理器方法返回的模型属性都存放到对应的request属性中,然后通过RequestDispatcher在服务器端把请求forword重定向到目标URL。
二、源码解析
package org.springframework.web.servlet.view;
import org.springframework.lang.Nullable;
import org.springframework.util.ClassUtils;
public class InternalResourceViewResolver extends UrlBasedViewResolver {
private static final boolean jstlPresent = ClassUtils.isPresent(
"javax.servlet.jsp.jstl.core.Config", InternalResourceViewResolver.class.getClassLoader());
@Nullable
private Boolean alwaysInclude;
/**
* Sets the default {@link #setViewClass view class} to {@link #requiredViewClass}:
* by default {@link InternalResourceView}, or {@link JstlView} if the JSTL API
* is present.
*/
public InternalResourceViewResolver() {
Class<?> viewClass = requiredViewClass();
if (InternalResourceView.class == viewClass && jstlPresent) {
viewClass = JstlView.class;
}
setViewClass(viewClass);
}
/**
* A convenience constructor that allows for specifying {@link #setPrefix prefix}
* and {@link #setSuffix suffix} as constructor arguments.
* @param prefix the prefix that gets prepended to view names when building a URL
* @param suffix the suffix that gets appended to view names when building a URL
* @since 4.3
*/
public InternalResourceViewResolver(String prefix, String suffix) {
this();
setPrefix(prefix);
setSuffix(suffix);
}
/**
* This resolver requires {@link InternalResourceView}.
*/
@Override
protected Class<?> requiredViewClass() {
return InternalResourceView.class;
}
/**
* Specify whether to always include the view rather than forward to it.
* <p>Default is "false". Switch this flag on to enforce the use of a
* Servlet include, even if a forward would be possible.
* @see InternalResourceView#setAlwaysInclude
*/
public void setAlwaysInclude(boolean alwaysInclude) {
this.alwaysInclude = alwaysInclude;
}
@Override
protected AbstractUrlBasedView buildView(String viewName) throws Exception {
InternalResourceView view = (InternalResourceView) super.buildView(viewName);
if (this.alwaysInclude != null) {
view.setAlwaysInclude(this.alwaysInclude);
}
view.setPreventDispatchLoop(true);
return view;
}
}
InternalResourceViewResolver 的实现源码其实很少,如上所示。
- 它将InternalResourceView 作为默认的View类。
- InternalResourceViewResolver 无论能不能解析都不会返回null,也就是说它拦截了所有的逻辑视图,让后续的解析器得不到执行,所以InternalResourceViewResolver 解析器必须放在最后
知行合一