http://www.jmatrix.org/spring/501.html
在了解IOC容器的基本实现的基础上,下面我们来看看,在典型的Web环境中,Spring IOC容器是如何在Web环境中被载入并起作用的。我们可以看到,对于MVC这部分,主要建立在IOC的基础上,AOP的特性应用得并不多。Spring并不是天生就能在Web容器中起作用的,同样也需要一个启动过程,把自己的IOC容器导入,并在Web容器中建立起来。
与对IoC容器的初始化的分析一样,我们同样看到了loadBeanDefinition对BeanDefinition的载入。在Web环境中,对定位BeanDefinition的Resource有特别的要求,对这个要求的处理体现在getDefaultConfigLocations方法的处理中。可以看到,在这里,使用了默认的BeanDefinition的配置路径,这个路径在XmlWebApplicationContext中,已经作为一个常量定义好了,这个常量就是/WEB-INF/applicationContext.xml。这里的loadBeanDefinition实现如下所示:
- public class XmlWebApplicationContext extends AbstractRefreshableWebApplicationContext {
- /** Default config location for the root context */
- //这里是设置缺省BeanDefinition的地方,在/WEB-INF/applicationContext.xml文件里,如果不特殊指定其他文件,IoC容器会从这里读取BeanDefinition来初始化IoC容器
- public static final String DEFAULT_CONFIG_LOCATION = "/WEB-INF/applicationContext.xml";
- /** Default prefix for building a config location for a namespace */
- public static final String DEFAULT_CONFIG_LOCATION_PREFIX = "/WEB-INF/";
- /** Default suffix for building a config location for a namespace */
- public static final String DEFAULT_CONFIG_LOCATION_SUFFIX = ".xml";
- //我们又看到了熟悉的loadBeanDefinition,就像我们前面对IOC容器的分析一样,这个加载过程在容器refresh()时启动。
- protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws IOException {
- // Create a new XmlBeanDefinitionReader for the given BeanFactory.
- // 对于XmlWebApplicationContext,当然是使用XmlBeanDefinitionReader来对BeanDefinition信息进行解析
- XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);
- // Configure the bean definition reader with this context's
- // resource loading environment.
- // 这里设置ResourceLoader,因为XmlWebApplicationContext是DefaultResource的子类,所以这里同样会使用DefaultResourceLoader来定位BeanDefinition
- beanDefinitionReader.setResourceLoader(this);
- beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this));
- // Allow a subclass to provide custom initialization of the reader,
- // then proceed with actually loading the bean definitions.
- initBeanDefinitionReader(beanDefinitionReader);
- //这里使用定义好的XmlBeanDefinitionReader来载入BeanDefinition
- loadBeanDefinitions(beanDefinitionReader);
- }
- protected void initBeanDefinitionReader(XmlBeanDefinitionReader beanDefinitionReader) {
- }
- //如果有多个BeanDefinition的文件定义,需要逐个载入,都是通过reader来完成的,这个初始化过程是由refreshBeanFactory方法来完成的,这里只是负责载入BeanDefinition
- protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws BeansException, IOException {
- String[] configLocations = getConfigLocations();
- if (configLocations != null) {
- for (String configLocation : configLocations) {
- reader.loadBeanDefinitions(configLocation);
- }
进入DispatcherServlet和MVC实现
完成了在Web环境中,IoC容器的建立以后,也就是在完成对ContextLoaderListener的初始化以后,Web容器开始初始化DispatcherServlet,接着,会执行DispatcherServlet持有的IoC容器的初始化过程,在这个初始化过程中,一个新的上下文被建立起来,这个DispatcherServlet持有的上下文,被设置为根上下文的子上下文。可以大致认为,根上下文是和Web应用相对应的一个上下文,而DispatcherServlet持有的上下文是和Servlet对应的一个上下文,在一个Web应用中,往往可以容纳多个Servlet存在;与此相对应,对于应用在Web容器中的上下体系,也是很类似的,一个根上下文可以作为许多Servlet上下文的双亲上下文。在DispatcherServlet,我们可以看到对MVC的初始化,是在DispatcherServlet的initStrategies完成的。
在这个初始化完成以后,会在上下文中建立器一个执行器于url的对应关系,这个对应关系可以让在url请求到来的时候,MVC可以检索到相应的控制器来进行处理,如以下代码所示:
- protected Object getHandlerInternal(HttpServletRequest request) throws Exception {
- //这里从request中得到请求的url路径
- String lookupPath = this.urlPathHelper.getLookupPathForRequest(request);
- //这里使用得到的url路径对Handler进行匹配,得到对应的Handler,如果没有对应的Hanlder,返回null,这样默认的Handler会被使用
- Object handler = lookupHandler(lookupPath, request);
- if (handler == null) {
- // We need to care for the default handler directly, since we need to
- // expose the PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE for it as well.
- Object rawHandler = null;
- if ("/".equals(lookupPath)) {
- rawHandler = getRootHandler();
- }
- if (rawHandler == null) {
- rawHandler = getDefaultHandler();
- }
- if (rawHandler != null) {
- validateHandler(rawHandler, request);
- handler = buildPathExposingHandler(rawHandler, lookupPath, null);
- }
- }
- if (handler != null && logger.isDebugEnabled()) {
- logger.debug("Mapping [" + lookupPath + "] to handler '" + handler + "'");
- }
- else if (handler == null && logger.isTraceEnabled()) {
- logger.trace("No handler mapping found for [" + lookupPath + "]");
- }
- return handler;
- }
- // lookupHandler是根据url路径,启动在handlerMap中对handler的检索,并最终返回handler对象
- protected Object lookupHandler(String urlPath, HttpServletRequest request) throws Exception {
- // Direct match?
- Object handler = this.handlerMap.get(urlPath);
- if (handler != null) {
- validateHandler(handler, request);
- return buildPathExposingHandler(handler, urlPath, null);
- }
- // Pattern match?
- String bestPathMatch = null;
- for (String registeredPath : this.handlerMap.keySet()) {
- if (getPathMatcher().match(registeredPath, urlPath) &&
- (bestPathMatch == null || bestPathMatch.length() < registeredPath.length())) {
- bestPathMatch = registeredPath;
- }
- }
- if (bestPathMatch != null) {
- handler = this.handlerMap.get(bestPathMatch);
- validateHandler(handler, request);
- String pathWithinMapping = getPathMatcher().extractPathWithinPattern(bestPathMatch, urlPath);
- Map<String, String> uriTemplateVariables =
- getPathMatcher().extractUriTemplateVariables(bestPathMatch, urlPath);
- return buildPathExposingHandler(handler, pathWithinMapping, uriTemplateVariables);
- }
- // No handler found...
- return null;
- }
oPost、doGet等,看这一系列方法的具体实现可以知道,请求的处理跳转到了processRequest函数中,最终进入DispatcherServlet的doService函数,详细的流程如:
上面的时序图展示了详细的请求处理流程,其中最重要的是doDispatch函数,其中包含了整个的处理逻辑,
- protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
- HttpServletRequest processedRequest = request;
- HandlerExecutionChain mappedHandler = null;
- int interceptorIndex = -1;
- //这里为视图准备好一个ModelAndView,这个ModelAndView持有handler处理请求的结果
- try {
- ModelAndView mv = null;
- boolean errorView = false;
- try {
- processedRequest = checkMultipart(request);
- // Determine handler for the current request.
- // 根据请求得到对应的handler,hander的注册以及getHandler的实现在前面已经分析过
- mappedHandler = getHandler(processedRequest, false);
- if (mappedHandler == null || mappedHandler.getHandler() == null) {
- noHandlerFound(processedRequest, response);
- return;
- }
- // Apply preHandle methods of registered interceptors.
- // 调用hander的拦截器,从HandlerExecutionChain中取出Interceptor进行前处理
- HandlerInterceptor[] interceptors = mappedHandler.getInterceptors();
- if (interceptors != null) {
- for (int i = 0; i < interceptors.length; i++) {
- HandlerInterceptor interceptor = interceptors[i];
- if (!interceptor.preHandle(processedRequest, response, mappedHandler.getHandler())) {
- triggerAfterCompletion(mappedHandler, interceptorIndex, processedRequest, response, null);
- return;
- }
- interceptorIndex = i;
- }
- }
- // Actually invoke the handler.
- // 这里是实际调用handler的地方,在执行handler之前,用HandlerAdapter先检查一下handler的合法性:是不是按Spring的要求编写的handler
- // handler处理的结果封装到ModelAndView对象,为视图提供展现数据
- HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler());
- //这里通过调用HandleAdapter的handle方法,实际上触发对Controller的handleRequest方法的调用
- mv = ha.handle(processedRequest, response, mappedHandler.getHandler());
- // Do we need view name translation?
- if (mv != null && !mv.hasView()) {
- mv.setViewName(getDefaultViewName(request));
- }
- // Apply postHandle methods of registered interceptors.
- if (interceptors != null) {
- for (int i = interceptors.length - 1; i >= 0; i--) {
- HandlerInterceptor interceptor = interceptors[i];
- interceptor.postHandle(processedRequest, response, mappedHandler.getHandler(), mv);
- }
- }
- }
- catch (ModelAndViewDefiningException ex) {
- logger.debug("ModelAndViewDefiningException encountered", ex);
- mv = ex.getModelAndView();
- }
- catch (Exception ex) {
- Object handler = (mappedHandler != null ? mappedHandler.getHandler() : null);
- mv = processHandlerException(processedRequest, response, handler, ex);
- errorView = (mv != null);
- }
- // Did the handler return a view to render?
- // 这里使用视图对ModelAndView数据的展现
- if (mv != null && !mv.wasCleared()) {
- render(mv, processedRequest, response);
- if (errorView) {
- WebUtils.clearErrorRequestAttributes(request);
- }
- }
- else {
- if (logger.isDebugEnabled()) {
- logger.debug("Null ModelAndView returned to DispatcherServlet with name '" + getServletName() +
- "': assuming HandlerAdapter completed request handling");
- }
- }
- // Trigger after-completion for successful outcome.
- triggerAfterCompletion(mappedHandler, interceptorIndex, processedRequest, response, null);
- }
- catch (Exception ex) {
- // Trigger after-completion for thrown exception.
- triggerAfterCompletion(mappedHandler, interceptorIndex, processedRequest, response, ex);
- throw ex;
- }
- catch (Error err) {
- ServletException ex = new NestedServletException("Handler processing failed", err);
- // Trigger after-completion for thrown exception.
- triggerAfterCompletion(mappedHandler, interceptorIndex, processedRequest, response, ex);
- throw ex;
- }
- finally {
- // Clean up any resources used by a multipart request.
- if (processedRequest != request) {
- cleanupMultipart(processedRequest);
- }
- }
- }
首先我们先看HandlerExecutionChain这个类中有些什么东西,
public class HandlerExecutionChain { private final Object handler; private HandlerInterceptor[] interceptors; private List interceptorList; …… }
这里面有两个关键的东西handler与interceptors,也即处理器对象与拦截器链表,联系到我们实际的编程,handler有可能是两种东西:(1)controller类对象;(2)controller中的方法对象(用的术语可能不太准确……)。而interceptors也即我们定义拦截器对象列表,如果说想在请求被处理之前做点什么就会弄一个。明白了这一点,再来看看在doDispatch函数中如果获得HandlerExecutionChain对象mappedHandler。
可以看到其实现在getHandler方法中:
protected HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception { for (HandlerMapping hm : this.handlerMappings) { …… HandlerExecutionChain handler = hm.getHandler(request); if (handler != null) { return handler; } } return null; }
函数的实现非常简单:遍历已注册的HandlerMapping列表,通过HandlerMapping对象的getHandler函数获取HandlerExecutionChain对象。至于HandlerMapping中的getHandler函数如何获取HandlerExecutionChain需要的处理器与拦截器,我只能说过程是繁琐的,原理是简单的,对于处理器对象(handler)根据不同的Mapping实现,其可以根据bean配置中的urlPath或者是方法的注解来寻找,这里不再细说。
顺着doDispatch函数的执行流程往下看,紧接着其通过getHandlerAdapter函数获得HandlerAdapter对象ha,然后就是又要重点照顾的一个调用:
mv = ha.handle(processedRequest, response, mappedHandler.getHandler());
随着调用HandlerAdapter的handle函数,Spring MVC便开始要真的“干实事”了,所谓的“干实事”也即开始调用执行我们编写的controller(控制逻辑)了。这里以两个HandlerAdapter的实现HttpRequestHandlerAdapter与AnnotationMethodHandlerAdapter来分析这个处理流程,在之前的一篇文章“Spring MVC实现分析——初始化过程”中有提到我自己的一个Spring MVC程序配置,以此为准进行展开:
HttpRequestHandlerAdapter的实现是最容易理解的,因为其handle的实现就是调用了处理器(handler)对象的handleRequest函数,借助F4看看Controller的继承体系,再看看AbstractController中handleRequest函数的实现
至于AnnotationMethodHandlerAdapter,其实现原理也是很容易理解的,我们已经知道其就是针对采用注解方式的方法映射的,实际应用中如:
@RequestMapping(method=RequestMethod.GET,value="/homeController.xhtml") protected ModelAndView handleRequestInternal(HttpServletRequest arg0, HttpServletResponse arg1) throws Exception { …… }
所以其handle的实现就是通过java的反射机制找到注解对应的处理方法,并调用完成控制逻辑的执行。
此时,让我们再次回到doDispatch的处理流程上来,在经过handle的“干实事”后,我们得到了ModelAndView对象,也即视图对象,很自然接下来的就是视图的渲染与展示了,这也是我们最后要分析的一个点。其入口是doDispatch中的一个函数调用:
processDispatchResult(processedRequest, response, mappedHandler, mv, dispatchException);