今天对《spring技术内幕》一书中有关springmvc组件的章节做一个简单总结。
springmvc的web环境配置
<servlet>
<servlet-name>application</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>application</servlet-name>
<!--<url-pattern>/*</url-pattern>-->
<url-pattern>/</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:META-INF/spring/camel-context.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
org.springframework.web.servlet.DispatcherServlet是springmvc的主类
org.springframework.web.context.ContextLoaderListener是springIOC容器的启动类,spring的配置文件路径通过contextConfigLocation属性声明。
IOC容器(ContextLoaderListener)启动
ioc容器的启动由org.springframework.web.context.ContextLoaderListener类来实现,ContextLoaderListener实现了ServletContextListener,所以web容器启动时,会自动启动ContextLoaderListener类并执行相应的初始化方法(ContextLoaderListener.contextInitialized)。
spring容器上下文的建立是由ContextListener完成的,流程如图所示。
ContextListener是ContextLoaderListener的基类,我们来看具体初始化ioc容器的方法
/**
* Initialize Spring's web application context for the given servlet context,
* using the application context provided at construction time, or creating a new one
* according to the "{@link #CONTEXT_CLASS_PARAM contextClass}" and
* "{@link #CONFIG_LOCATION_PARAM contextConfigLocation}" context-params.
* @param servletContext current servlet context
* @return the new WebApplicationContext
* @see #ContextLoader(WebApplicationContext)
* @see #CONTEXT_CLASS_PARAM
* @see #CONFIG_LOCATION_PARAM
*/
public WebApplicationContext initWebApplicationContext(ServletContext servletContext) {
// 判断web容器servletContext中是否已经由springioc的上下文对象
if (servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE) != null) {
throw new IllegalStateException(
"Cannot initialize context because there is already a root application context present - " +
"check whether you have multiple ContextLoader* definitions in your web.xml!");
}
Log logger = LogFactory.getLog(ContextLoader.class);
servletContext.log("Initializing Spring root WebApplicationContext");
if (logger.isInfoEnabled()) {
logger.info("Root WebApplicationContext: initialization started");
}
long startTime = System.currentTimeMillis();
try {
// 创建springioc的上下对象
if (this.context == null) {
this.context = createWebApplicationContext(servletContext);
}
if (this.context instanceof ConfigurableWebApplicationContext) {
ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) this.context;
if (!cwac.isActive()) {
if (cwac.getParent() == null) {
// 设置容器的双亲容器
ApplicationContext parent = loadParentContext(servletContext);
cwac.setParent(parent);
}
// 执行ioc容器的refresh方法,开始真正启动容器
configureAndRefreshWebApplicationContext(cwac, servletContext);
}
}
// 将生成的ioc容器上下文对象设置到servletContext中,以后在web容器中,可以通过WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE获取到ioc容器
servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context);
ClassLoader ccl = Thread.currentThread().getContextClassLoader();
if (ccl == ContextLoader.class.getClassLoader()) {
currentContext = this.context;
}
else if (ccl != null) {
currentContextPerThread.put(ccl, this.context);
}
if (logger.isDebugEnabled()) {
logger.debug("Published root WebApplicationContext as ServletContext attribute with name [" +
WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE + "]");
}
if (logger.isInfoEnabled()) {
long elapsedTime = System.currentTimeMillis() - startTime;
logger.info("Root WebApplicationContext: initialization completed in " + elapsedTime + " ms");
}
return this.context;
}
catch (RuntimeException ex) {
logger.error("Context initialization failed", ex);
servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ex);
throw ex;
}
catch (Error err) {
logger.error("Context initialization failed", err);
servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, err);
throw err;
}
}
protected void configureAndRefreshWebApplicationContext(ConfigurableWebApplicationContext wac, ServletContext sc) {
if (ObjectUtils.identityToString(wac).equals(wac.getId())) {
String idParam = sc.getInitParameter(CONTEXT_ID_PARAM);
if (idParam != null) {
wac.setId(idParam);
}
else {
wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX +
ObjectUtils.getDisplayString(sc.getContextPath()));
}
}
wac.setServletContext(sc);
// 获取web.xml中配置的contextConfigLocation属性
String configLocationParam = sc.getInitParameter(CONFIG_LOCATION_PARAM);
if (configLocationParam != null) {
// 给容器设置配置属性的路径
wac.setConfigLocation(configLocationParam);
}
ConfigurableEnvironment env = wac.getEnvironment();
if (env instanceof ConfigurableWebEnvironment) {
((ConfigurableWebEnvironment) env).initPropertySources(sc, null);
}
customizeContext(sc, wac);
// 好熟悉的方法,不解释~
wac.refresh();
}
接着看下创建容器对象的方法(ContextLoader.createWebApplicationContext)
protected WebApplicationContext createWebApplicationContext(ServletContext sc) {
// 获取ioc容器的class对象,如:org.springframework.web.context.support.XmlWebApplicationContext
Class<?> contextClass = determineContextClass(sc);
if (!ConfigurableWebApplicationContext.class.isAssignableFrom(contextClass)) {
throw new ApplicationContextException("Custom context class [" + contextClass.getName() +
"] is not of type [" + ConfigurableWebApplicationContext.class.getName() + "]");
}
return (ConfigurableWebApplicationContext) BeanUtils.instantiateClass(contextClass);
}
protected Class<?> determineContextClass(ServletContext servletContext) {
// 若我们在web.xml中指定了contextClass属性,则使用自定义ioc容器对象
String contextClassName = servletContext.getInitParameter(CONTEXT_CLASS_PARAM);
if (contextClassName != null) {
try {
return ClassUtils.forName(contextClassName, ClassUtils.getDefaultClassLoader());
}
catch (ClassNotFoundException ex) {
throw new ApplicationContextException(
"Failed to load custom context class [" + contextClassName + "]", ex);
}
}
else {
// 否则使用默认的ioc容器,org.springframework.web.context.support.XmlWebApplicationContext
// 默认ioc容器配置在ContextLoader.properties文件中
contextClassName = defaultStrategies.getProperty(WebApplicationContext.class.getName());
try {
return ClassUtils.forName(contextClassName, ContextLoader.class.getClassLoader());
}
catch (ClassNotFoundException ex) {
throw new ApplicationContextException(
"Failed to load default context class [" + contextClassName + "]", ex);
}
}
}
默认的ioc容器获取方式
String contextClassName = defaultStrategies.getProperty(WebApplicationContext.class.getName());
return ClassUtils.forName(contextClassName, ContextLoader.class.getClassLoader());
ContextLoader.properties文件内容
org.springframework.web.context.WebApplicationContext=org.springframework.web.context.support.XmlWebApplicationContext
至此,org.springframework.web.context.ContextLoaderListener监听类的使命基本完成,将spring的ioc容器初始化完成并设置到了web容器的servletContext对象的属性中,并可以通过WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE获取到ioc容器的上下文对象。
DispatcherServlet
- DispatcherServlet的启动和初始化
DispatcherServlet,类的继承关系
DispatcherServlet的大致处理过程
web容器启动–>HttpServlet.init()–>FrameworkServlet.initServletBean()–>FrameworkServlet.initWebApplicationContext()–>FrameworkServlet.createWebApplicationContext()–>DispatcherServlet.initStrategies()
这是一个DispatcherServlet启动和初始化的大致调用链流程。
接下来研究一下启动和初始化的具体过程,从FrameworkServlet.initWebApplicationContext为入口进行研究
protected WebApplicationContext initWebApplicationContext() {
// 从servletContext中通过WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE,获取
// ContextLoaderListener生成的根ioc上下文对象
WebApplicationContext rootContext =
WebApplicationContextUtils.getWebApplicationContext(getServletContext());
WebApplicationContext wac = null;
if (this.webApplicationContext != null) {
wac = this.webApplicationContext;
if (wac instanceof ConfigurableWebApplicationContext) {
ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) wac;
if (!cwac.isActive()) {
if (cwac.getParent() == null) {
cwac.setParent(rootContext);
}
configureAndRefreshWebApplicationContext(cwac);
}
}
}
if (wac == null) {
wac = findWebApplicationContext();
}
// 根据springmvc自己的配置文件创建子ioc容器对象,并将rootContext设置为双亲容器
if (wac == null) {
wac = createWebApplicationContext(rootContext);
}
if (!this.refreshEventReceived) {
// 初始化DispatcherServlet的HandlerMappings、HandlerAdapters等mvc组件
onRefresh(wac);
}
// 将当前建立的容器对象设置到servletContext对象中
if (this.publishContext) {
String attrName = getServletContextAttributeName();
getServletContext().setAttribute(attrName, wac);
if (this.logger.isDebugEnabled()) {
this.logger.debug("Published WebApplicationContext of servlet '" + getServletName() +
"' as ServletContext attribute with name [" + attrName + "]");
}
}
return wac;
}
我们看一下springmvc建立ioc容器的具体方法(FrameworkServlet.createWebApplicationContext)
protected WebApplicationContext createWebApplicationContext(ApplicationContext parent) {
Class<?> contextClass = getContextClass();
if (this.logger.isDebugEnabled()) {
this.logger.debug("Servlet with name '" + getServletName() +
"' will try to create custom WebApplicationContext context of class '" +
contextClass.getName() + "'" + ", using parent context [" + parent + "]");
}
if (!ConfigurableWebApplicationContext.class.isAssignableFrom(contextClass)) {
throw new ApplicationContextException(
"Fatal initialization error in servlet with name '" + getServletName() +
"': custom WebApplicationContext class [" + contextClass.getName() +
"] is not of type ConfigurableWebApplicationContext");
}
ConfigurableWebApplicationContext wac =
(ConfigurableWebApplicationContext) BeanUtils.instantiateClass(contextClass);
wac.setEnvironment(getEnvironment());
// 将ContextLoaderListener生成的根ioc上下文对象设置为双亲上下文
wac.setParent(parent);
wac.setConfigLocation(getContextConfigLocation());
// 设置容器上下文对象的Namespace、调用refresh()
configureAndRefreshWebApplicationContext(wac);
return wac;
}
这里的wac.setConfigLocation(getContextConfigLocation())和Namespace会在此处用到
/**
* 获取springmvc的配置文件路径,若配置了DispatcherServlet的contextConfigLocation属性,则加载
* contextConfigLocation的值,如contextConfigLocation没有指定,则根据Namespace获取"/WEB-INF/$(namespace).xml",若namespace没有指定,生成一个默认的namespace "$(ServletName)-servlet"
* /
protected String[] getConfigLocations() {
return (this.configLocations != null ? this.configLocations : getDefaultConfigLocations());
}
/**
* 获取默认配置文件路径"/WEB-INF/applicationContext.xml" or "/WEB-INF/test-servlet.xml"
* /
protected String[] getDefaultConfigLocations() {
if (getNamespace() != null) {
return new String[] {DEFAULT_CONFIG_LOCATION_PREFIX + getNamespace() + DEFAULT_CONFIG_LOCATION_SUFFIX};
}
else {
return new String[] {DEFAULT_CONFIG_LOCATION};
}
}
这样DispatcherServlet中的ioc容器已经建立起来了,对于一个bean的查找规则,系统会先从DispatcherServlet的双亲ioc容器中查找,如果找不到,再从DispatcherServlet自己的ioc容器中进行查找。
接下来便是对spring mvc框架的初始化,入口为DispatcherServlet.initStrategies()
protected void initStrategies(ApplicationContext context) {
initMultipartResolver(context);
initLocaleResolver(context);
initThemeResolver(context);
initHandlerMappings(context);
initHandlerAdapters(context);
initHandlerExceptionResolvers(context);
initRequestToViewNameTranslator(context);
initViewResolvers(context);
initFlashMapManager(context);
}
这里将对三个组件的初始化方法HandlerMappings、HandlerAdapters做进一步研究
下面我们来分析下HandlerMappings的初始化
private void initHandlerMappings(ApplicationContext context) {
this.handlerMappings = null;
// 默认加载所有的HandlerMappings
if (this.detectAllHandlerMappings) {
Map<String, HandlerMapping> matchingBeans =
BeanFactoryUtils.beansOfTypeIncludingAncestors(context, HandlerMapping.class, true, false);
if (!matchingBeans.isEmpty()) {
this.handlerMappings = new ArrayList<HandlerMapping>(matchingBeans.values());
AnnotationAwareOrderComparator.sort(this.handlerMappings);
}
}
else {
try {
// 只加载指定的beanName为"handlerMapping"的HandlerMappings
HandlerMapping hm = context.getBean(HANDLER_MAPPING_BEAN_NAME, HandlerMapping.class);
this.handlerMappings = Collections.singletonList(hm);
}
catch (NoSuchBeanDefinitionException ex) {
}
}
// 从springmvc框架配置文件中加载默认的HandlerMappings
if (this.handlerMappings == null) {
this.handlerMappings = getDefaultStrategies(context, HandlerMapping.class);
if (logger.isDebugEnabled()) {
logger.debug("No HandlerMappings found in servlet '" + getServletName() + "': using default");
}
}
}
这里需要做一个说明
1)我们通过mvc:annotation-driven注解,会自动在容器中注册两个HandlerMappings
-> “org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping”
-> “org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping”
2)若我们没有做任何HandlerMappings的配置,mvc框架会根据DispatcherServlet.properties配置文件,加载两个HandlerMappings
-> “org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping”
-> “org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping”
- MVC处理HTTP分发请求
HandlerMapping是mvc非常重要的组件,它持有着url与对应controller的映射关系。
HandlerMapping实现
下面我们通过常用的org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping来解析一下url与对应controller的映射关系的注册过程。
RequestMappingHandlerMapping继承关系
RequestMappingHandlerMapping在向容器注册时,ioc会回调afterPropertiesSet方法,我们跟进到AbstractHandlerMethodMapping.detectHandlerMethods方法
protected void detectHandlerMethods(final Object handler) {
Class<?> handlerType = (handler instanceof String ?
getApplicationContext().getType((String) handler) : handler.getClass());
final Class<?> userType = ClassUtils.getUserClass(handlerType);
// 建立controller中的Method对象与url的映射关系
Map<Method, T> methods = MethodIntrospector.selectMethods(userType,
new MethodIntrospector.MetadataLookup<T>() {
@Override
public T inspect(Method method) {
// 建立Method对象与url映射关系的具体实现,由具体子类实现
return getMappingForMethod(method, userType);
}
});
if (logger.isDebugEnabled()) {
logger.debug(methods.size() + " request handler methods found on " + userType + ": " + methods);
}
for (Map.Entry<Method, T> entry : methods.entrySet()) {
// 将映射关系注册到框架中
registerHandlerMethod(handler, entry.getKey(), entry.getValue());
}
}
我们看一下具体的注册过程(AbstractHandlerMethodMapping.MappingRegistry.register())
public void register(T mapping, Object handler, Method method) {
this.readWriteLock.writeLock().lock();
try {
// 创建HandlerMethod对象实例
HandlerMethod handlerMethod = createHandlerMethod(handler, method);
assertUniqueMethodMapping(handlerMethod, mapping);
if (logger.isInfoEnabled()) {
logger.info("Mapped \"" + mapping + "\" onto " + handlerMethod);
}
// 将url路径与HandlerMethod对象进行映射
this.mappingLookup.put(mapping, handlerMethod);
List<String> directUrls = getDirectUrls(mapping);
for (String url : directUrls) {
// 对url进行正则加工,可以进行模糊匹配
this.urlLookup.add(url, mapping);
}
String name = null;
if (getNamingStrategy() != null) {
name = getNamingStrategy().getName(handlerMethod, mapping);
addMappingName(name, handlerMethod);
}
CorsConfiguration corsConfig = initCorsConfiguration(handler, method, mapping);
if (corsConfig != null) {
this.corsLookup.put(handlerMethod, corsConfig);
}
// 建立url与MappingRegistration的映射关系,MappingRegistration中有handlerMethod信息
this.registry.put(mapping, new MappingRegistration<T>(mapping, handlerMethod, directUrls, name));
}
finally {
this.readWriteLock.writeLock().unlock();
}
}
至此,url与controller中的mothed映射关系已经建立,存储在2个map中
AbstractHandlerMethodMapping.MappingRegistry中的
结下来mvc框架就可以对请求进行分发处理了
先看一下请求的处理过程
请求调用链
FrameworkServlet.doGet —-> FrameworkServlet.processRequest —-> DispatcherServlet.doService —-> DispatcherServlet.doDispatch
protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
HttpServletRequest processedRequest = request;
HandlerExecutionChain mappedHandler = null;
boolean multipartRequestParsed = false;
WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
try {
ModelAndView mv = null;
Exception dispatchException = null;
try {
processedRequest = checkMultipart(request);
multipartRequestParsed = (processedRequest != request);
// 获取处理当前请求的目标调用方法元信息对象HandlerExecutionChain.
mappedHandler = getHandler(processedRequest);
if (mappedHandler == null || mappedHandler.getHandler() == null) {
noHandlerFound(processedRequest, response);
return;
}
// 获取当前request请求的Adapter处理适配器.
HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler());
String method = request.getMethod();
boolean isGet = "GET".equals(method);
if (isGet || "HEAD".equals(method)) {
long lastModified = ha.getLastModified(request, mappedHandler.getHandler());
if (logger.isDebugEnabled()) {
logger.debug("Last-Modified value for [" + getRequestUri(request) + "] is: " + lastModified);
}
if (new ServletWebRequest(request, response).checkNotModified(lastModified) && isGet) {
return;
}
}
// 执行Interceptor拦截器的preHandle方法
if (!mappedHandler.applyPreHandle(processedRequest, response)) {
return;
}
// Adapter处理适配器执行controller中的目标方法.
mv = ha.handle(processedRequest, response, mappedHandler.getHandler());
if (asyncManager.isConcurrentHandlingStarted()) {
return;
}
applyDefaultViewName(processedRequest, mv);
// 执行Interceptor拦截器的postHandle方法
mappedHandler.applyPostHandle(processedRequest, response, mv);
}
catch (Exception ex) {
dispatchException = ex;
}
// 调用render返回view视图结果
processDispatchResult(processedRequest, response, mappedHandler, mv, dispatchException);
}
catch (Exception ex) {
triggerAfterCompletion(processedRequest, response, mappedHandler, ex);
}
catch (Error err) {
triggerAfterCompletionWithError(processedRequest, response, mappedHandler, err);
}
finally {
if (asyncManager.isConcurrentHandlingStarted()) {
// Instead of postHandle and afterCompletion
if (mappedHandler != null) {
mappedHandler.applyAfterConcurrentHandlingStarted(processedRequest, response);
}
}
else {
// Clean up any resources used by a multipart request.
if (multipartRequestParsed) {
cleanupMultipart(processedRequest);
}
}
}
}
doDispatch方法基本实现了mvc框架的整个请求调用和响应的流程
大致分为3个步骤
1)getHandler 通过url获取到需要调用的controller中的目标方法
2)获取Adapter处理适配器
3)由Adapter的handle方法执行controller中的目标方法的具体的调用过程,并将方法的返回结果设置到ModelAndView对象中
4)调用render方法response视图
controller中的目标方法的获取AbstractHandlerMapping.getHandler
public final HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception {
// 根据请求路径获取对应的controller目标方法信息
Object handler = getHandlerInternal(request);
if (handler == null) {
// 获取/路径的目标方法信息
handler = getDefaultHandler();
}
if (handler == null) {
return null;
}
if (handler instanceof String) {
String handlerName = (String) handler;
handler = getApplicationContext().getBean(handlerName);
}
// 将调用目标信息封装到HandlerExecutionChain对象中
HandlerExecutionChain executionChain = getHandlerExecutionChain(handler, request);
if (CorsUtils.isCorsRequest(request)) {
CorsConfiguration globalConfig = this.corsConfigSource.getCorsConfiguration(request);
CorsConfiguration handlerConfig = getCorsConfiguration(handler, request);
CorsConfiguration config = (globalConfig != null ? globalConfig.combine(handlerConfig) : handlerConfig);
executionChain = getCorsHandlerExecutionChain(request, executionChain, config);
}
return executionChain;
}
@Override
protected HandlerMethod getHandlerInternal(HttpServletRequest request) throws Exception {
String lookupPath = getUrlPathHelper().getLookupPathForRequest(request);
if (logger.isDebugEnabled()) {
logger.debug("Looking up handler method for path " + lookupPath);
}
this.mappingRegistry.acquireReadLock();
try {
HandlerMethod handlerMethod = lookupHandlerMethod(lookupPath, request);
if (logger.isDebugEnabled()) {
if (handlerMethod != null) {
logger.debug("Returning handler method [" + handlerMethod + "]");
}
else {
logger.debug("Did not find handler method for [" + lookupPath + "]");
}
}
return (handlerMethod != null ? handlerMethod.createWithResolvedBean() : null);
}
finally {
this.mappingRegistry.releaseReadLock();
}
}
protected HandlerMethod lookupHandlerMethod(String lookupPath, HttpServletRequest request) throws Exception {
List<Match> matches = new ArrayList<Match>();
// 从url和controller目标对象映射关系的map中获取url对应的目标方法信息
List<T> directPathMatches = this.mappingRegistry.getMappingsByUrl(lookupPath);
if (directPathMatches != null) {
addMatchingMappings(directPathMatches, matches, request);
}
if (matches.isEmpty()) {
addMatchingMappings(this.mappingRegistry.getMappings().keySet(), matches, request);
}
if (!matches.isEmpty()) {
Comparator<Match> comparator = new MatchComparator(getMappingComparator(request));
Collections.sort(matches, comparator);
if (logger.isTraceEnabled()) {
logger.trace("Found " + matches.size() + " matching mapping(s) for [" +
lookupPath + "] : " + matches);
}
Match bestMatch = matches.get(0);
if (matches.size() > 1) {
if (CorsUtils.isPreFlightRequest(request)) {
return PREFLIGHT_AMBIGUOUS_MATCH;
}
Match secondBestMatch = matches.get(1);
if (comparator.compare(bestMatch, secondBestMatch) == 0) {
Method m1 = bestMatch.handlerMethod.getMethod();
Method m2 = secondBestMatch.handlerMethod.getMethod();
throw new IllegalStateException("Ambiguous handler methods mapped for HTTP path '" +
request.getRequestURL() + "': {" + m1 + ", " + m2 + "}");
}
}
handleMatch(bestMatch.mapping, lookupPath, request);
return bestMatch.handlerMethod;
}
else {
return handleNoMatch(this.mappingRegistry.getMappings().keySet(), lookupPath, request);
}
}
可以看到这里的url和controller目标方法的映射关系是从AbstractHandlerMethodMapping.MappingRegistry中的
这两个map对象中获取的,上面我们在HandlerMapping的初始化过程中有提到过
之后会获取对应的Adapter并调用其handle方法
⚠️:如果配置了多个Adapter,只有第一个会执行,HandlerAdapter只会执行一个,其他的自动忽略。
我们这里研究的是org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter
通过注解在初始化HandlerAdapter时被设置到ioc容器中
这个Adaper会执行controller中的目标方法的具体的调用过程
Object returnValue = doInvoke(args);
并将方法的返回结果根据类型用对应的HandlerMethodReturnValueHandler进行处理
并将returnValue设置到ModelAndViewContainer对象中。
- MVC视图呈现
视图继承结构
Adapter返回的ModelAndView会被DispatcherServlet.render方法处理
protected void render(ModelAndView mv, HttpServletRequest request, HttpServletResponse response) throws Exception {
Locale locale = this.localeResolver.resolveLocale(request);
response.setLocale(locale);
View view;
if (mv.isReference()) {
// 获取试图解析器
view = resolveViewName(mv.getViewName(), mv.getModelInternal(), locale, request);
if (view == null) {
throw new ServletException("Could not resolve view with name '" + mv.getViewName() +
"' in servlet with name '" + getServletName() + "'");
}
}
else {
view = mv.getView();
if (view == null) {
throw new ServletException("ModelAndView [" + mv + "] neither contains a view name nor a " +
"View object in servlet with name '" + getServletName() + "'");
}
}
if (logger.isDebugEnabled()) {
logger.debug("Rendering view [" + view + "] in DispatcherServlet with name '" + getServletName() + "'");
}
try {
// 执行视图解析器中的render方法
view.render(mv.getModelInternal(), request, response);
}
catch (Exception ex) {
if (logger.isDebugEnabled()) {
logger.debug("Error rendering view [" + view + "] in DispatcherServlet with name '" +
getServletName() + "'", ex);
}
throw ex;
}
}
对于viewResolver对象的获取如果我们配置解析器,没有指定beanName为viewResolver的解析器,框架会根据DispatcherServlet.properties配置文件用默认的解析器org.springframework.web.servlet.view.InternalResourceViewResolver
@Override
public void render(Map<String, ?> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
if (logger.isTraceEnabled()) {
logger.trace("Rendering view with name '" + this.beanName + "' with model " + model +
" and static attributes " + this.staticAttributes);
}
Map<String, Object> mergedModel = createMergedOutputModel(model, request, response);
prepareResponse(request, response);
// 由具体的视图解析器实现
renderMergedOutputModel(mergedModel, getRequestToExpose(request), response);
}
/**
* 以jsp解析器org.springframework.web.servlet.view.InternalResourceViewResolver为例
*/
@Override
protected void renderMergedOutputModel(
Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
// 将ModelAndView中的数据设置为request的属性,request.setAttribute(modelName, modelValue);
exposeModelAsRequestAttributes(model, request);
exposeHelpers(request);
// 获取转发路径.
String dispatcherPath = prepareForRendering(request, response);
// 将转发路径设置到request对象中request.getRequestDispatcher(path)
RequestDispatcher rd = getRequestDispatcher(request, dispatcherPath);
if (rd == null) {
throw new ServletException("Could not get RequestDispatcher for [" + getUrl() +
"]: Check that the corresponding file exists within your web application archive!");
}
if (useInclude(request, response)) {
response.setContentType(getContentType());
if (logger.isDebugEnabled()) {
logger.debug("Including resource [" + getUrl() + "] in InternalResourceView '" + getBeanName() + "'");
}
rd.include(request, response);
}
else {
if (logger.isDebugEnabled()) {
logger.debug("Forwarding to resource [" + getUrl() + "] in InternalResourceView '" + getBeanName() + "'");
}
// forword将请求转发,结束
rd.forward(request, response);
}
}
其实以org.springframework.web.servlet.view.InternalResourceViewResolver视图为例,主要做了2件事
1)将Adapter返回的ModelAndView对象中的数据设置为request对象中属性
2)执行RequestDispatcher.forward(request, response),执行请求跳转
至此,springmvc执行流程大致结束