Spring MVC(1)2018-08-05

 我们知道DispatcherServelt是Spring MVC的前端控制器(Font Controller),作为一个前端控制器,所有的web请求都需要通过它来处理,进行转发、匹配、数据处理后,并转由页面进行展现,因此这个DispatcherServelt可以看成Spring MVC实现种的最为核心的部分。接下来我们从DispatcherServelt的初始化和处理http请求两方面来看看。
&emps;先看看DispatcherServelt:


DispatcherServelt.png

 从上面的继承关系可以看出DispatcherServelt继承的对象有:
&emps;1、ApplicationContextAware:这个接口可以获取到Spring的上下文applicationContext。
 2、EvironmentAware:这个接口可以获取系统的环境变量信息
 3、Servelt:现 Servlet 接口的抽象类专门用来处理 HTTP 请求

DispatcherServelt的初始化:

 DispatcherServelt作为一个Servelt,当DispatcherServelt创建的时候会执行init()初始化方法:
DispatcherServelt从HttpServletBean中的继承的init()方法

public final void init() throws ServletException {
        if (this.logger.isDebugEnabled()) {
            this.logger.debug("Initializing servlet '" + this.getServletName() + "'");
        }
        //获取Servelt的初始化参数,对Bean属性进行配置
        PropertyValues pvs = new HttpServletBean.ServletConfigPropertyValues(this.getServletConfig(), this.requiredProperties);
        if (!pvs.isEmpty()) {
            try {
                BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(this);
                ResourceLoader resourceLoader = new ServletContextResourceLoader(this.getServletContext());
                bw.registerCustomEditor(Resource.class, new ResourceEditor(resourceLoader, this.getEnvironment()));
                this.initBeanWrapper(bw);
                bw.setPropertyValues(pvs, true);
            } catch (BeansException var4) {
                if (this.logger.isErrorEnabled()) {
                    this.logger.error("Failed to set bean properties on servlet '" + this.getServletName() + "'", var4);
                }

                throw var4;
            }
        }
        //进行具体的初始化
        this.initServletBean();
        if (this.logger.isDebugEnabled()) {
            this.logger.debug("Servlet '" + this.getServletName() + "' configured successfully");
        }

    }

initServletBean()是在FrameworkServelt中完成的:

protected final void initServletBean() throws ServletException {
        this.getServletContext().log("Initializing Spring FrameworkServlet '" + this.getServletName() + "'");
        if (this.logger.isInfoEnabled()) {
            this.logger.info("FrameworkServlet '" + this.getServletName() + "': initialization started");
        }

        long startTime = System.currentTimeMillis();

        try {
           //初始化上下文
            this.webApplicationContext = this.initWebApplicationContext();
            this.initFrameworkServlet();
        } catch (RuntimeException | ServletException var5) {
            this.logger.error("Context initialization failed", var5);
            throw var5;
        }

        if (this.logger.isInfoEnabled()) {
            long elapsedTime = System.currentTimeMillis() - startTime;
            this.logger.info("FrameworkServlet '" + this.getServletName() + "': initialization completed in " + elapsedTime + " ms");
        }

    }

接着往下看:

 protected WebApplicationContext initWebApplicationContext() {
        //首先通过ServletContext获得spring容器,因为子容器springMVC要和父容器spring容器进行关联
        WebApplicationContext rootContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
        //定义springMVC容器wac
        WebApplicationContext wac = null;
        //否已经存在了容器实例,存在的话直接赋值给wac,给springMVC容器设置父容器
        //最后调用刷新函数configureAndRefreshWebApplicationContext(wac),作用是把springMVC.xml的配置信息加载到容器中去
        if (this.webApplicationContext != null) {
            wac = this.webApplicationContext;
            if (wac instanceof ConfigurableWebApplicationContext) {
                ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext)wac;
                if (!cwac.isActive()) {
                  //在Spring上下文还未刷新完之前  ApplicationContext是通过调用refresh方法来进行bean的加载初始化装配等一系列动作
                    if (cwac.getParent() == null) {
                        cwac.setParent(rootContext);
                    }
                   //ApplicationContext是通过调用refresh方法来进行bean的加载初始化装配等一系列动作
                    this.configureAndRefreshWebApplicationContext(cwac);
                }
            }
        }

        if (wac == null) {
            // 在ServletContext中寻找是否有springMVC容器,初次运行是没有的,springMVC初始化完毕ServletContext就有了springMVC容器
            wac = this.findWebApplicationContext();
        }
      //当wac既没有注册到容器中的,也没在ServletContext找得到,此时就要新建一个springMVC容器
        if (wac == null) {
            wac = this.createWebApplicationContext(rootContext);
        }

        if (!this.refreshEventReceived) {
            //到这里mvc的容器已经创建完毕,接着才是真正调用DispatcherServlet的初始化方法onRefresh(wac)
            this.onRefresh(wac);
        }
        //将springMVC容器存放到ServletContext中去,方便下次取出来
        if (this.publishContext) {
            String attrName = this.getServletContextAttributeName();
            this.getServletContext().setAttribute(attrName, wac);
            if (this.logger.isDebugEnabled()) {
                this.logger.debug("Published WebApplicationContext of servlet '" + this.getServletName() + "' as ServletContext attribute with name [" + attrName + "]");
            }
        }

        return wac;
    }

接下来看创建springMVC 的ioc容器方法createWebApplicationContext(WebApplicationContext parent)

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");
        }
        //实例化空白的ioc容器
        ConfigurableWebApplicationContext wac =
                (ConfigurableWebApplicationContext) BeanUtils.instantiateClass(contextClass);
        //给容器设置环境
        wac.setEnvironment(getEnvironment());
        //给容器设置父容器(就是spring容器),两个ioc容器关联在一起了
        wac.setParent(parent);
        //给容器加载springMVC.xml的配置信息,bean注入,注解,扫描等等
        wac.setConfigLocation(getContextConfigLocation());
        //上面提到过这方法,刷新容器,根据springMVC.xml配置文件完成初始化操作,此时springMVC容器创建完成
        configureAndRefreshWebApplicationContext(wac);

        return wac;
    }

接下来看DispatcherServlet的onRefresh(ApplicationContext context)方法

 protected void onRefresh(ApplicationContext context) {
        initStrategies(context);
    }

protected void initStrategies(ApplicationContext context) {
         initMultipartResolver(context);//文件上传解析
        initLocaleResolver(context);//本地解析
        initThemeResolver(context);//主题解析
        initHandlerMappings(context);//url请求映射
        initHandlerAdapters(context);//初始化真正调用controloler方法的类
        initHandlerExceptionResolvers(context);//异常解析
        initRequestToViewNameTranslator(context);//视图名称翻译器
        initViewResolvers(context);//视图解析
        initFlashMapManager(context);//重定向数据管理器
    }

总结:

1、调用DispatcherServlet父类的父类HttpServletBean的init()方法,把配置DispatcherServlet的初始化参数设置到DispatcherServlet中,调用子类FrameworkServlet的initServletBean()方法
2、initServletBean()创建springMVC容器实例并初始化容器,并且和spring父容器进行关联,使得mvc容器能访问spring容器里面的bean,之后调用子类DispatcherServlet的onRefresh(ApplicationContext context)方法
3、onRefresh(ApplicationContext context)进行DispatcherServlet的策略组件初始化工作,url映射初始化,文件解析初始化,运行适配器初始化等等。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容