博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
SpringMVC-----ContextLoaderListener
阅读量:4346 次
发布时间:2019-06-07

本文共 8956 字,大约阅读时间需要 29 分钟。

前言

Spring框架提供了构建Web应用程序的全功能MVC模块。通过策略接口,Spring框架是高度可配置的,而且支持多种视图技术,例如JavaServer Pages(JSP)技术、Velocity、Tiles、iText和POI。Spring MVC框架并不知道使用的视图,所以不会强迫你只是用JSP技术,SpringMVC分离了控制器、模型对象、分派器以及处理程序对象的角色,这种分离让它们更容易进行定制。

Spring的MVC是基于Servlet功能实现的,通过实现Servlet接口的DispatcherServlet来封装其核心功能实现,通过将请求分派给处理程序,同时带有可配置的处理程序映射、视图解析、本地语言、主题解析以及上载文件支持。默认的处理程序是非常简单的Controller接口,只有一个方法ModelAndView handleRequest(request,response)。Spring提供了一个控制器层次结构,可以派生子类。如果应用程序需要处理用户输入表单,那么可以继承AbstractFromController。如果需要把多页输入处理到一个表单,那么可以继承AbstractWizardFormController。

SpringMVC或者其他比较成熟的MVC框架而言,解决的问题如下:

(1)将Web页面的请求传给服务器。

(2)根据不同的请求处理不同的逻辑单元。

(3)返回处理结果数据并跳转至响应的页面。

ContextLoaderListener

对于SpringMVC功能实现的分析,我们首先从web.xml开始,在web.xml文件中我们首先配置的就是ContextLoaderListener,那么它提供的功能有哪些又是如何实现的呢?

当使用编程方式的时候我们可以直接将Spring配置信息作为参数传入Spring容器中,如:

ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");

但是在Web下,我们需要更多的是与Web环境相互结合,通常的办法是将路径以context-param的方式注册并使用ContextLoaderListener进行监听读取。

ContextLoaderListener的作用就是启动Web容器时,自动装配ApplicationContext的配置信息。因为它实现了ServletContextListener这个接口,在web.xml配置这个监听器,启动容器时,就会默认执行它实现的方法。使用ServletContextListener接口,开发者能够在为客户端请求提供服务之前向ServletContext中添加任意的对象。这个对象在ServletContext启动的时候被初始化,然后在ServletContext整个运行期间都是可见的。

每一个Web应用都有一个ServletContext与之相关联。ServletContext对象在应用启动时被创建,在应用关闭的时候被销毁。ServletContext在全局范围内有效,类似于应用中的一个全局变量。

在ServletContextListener中的核心逻辑便是初始化WebApplicationContext实例并存放至ServletContext中。

ServletContextListener的使用

正式分析代码之前我们还是先了解ServletContextListener的使用。

(1)创建自定义ServletContextListener

首先我们创建ServletContextListener,目标是在启动的添加自定义的属性,以便于在全局范围内可以随时调用。系统启动的时候会调用ServletContextListener实现类的contextInitialized方法,所以需要在这个方法中实现我们的初始化逻辑。

public class MyContextListener implements ServletContextListener {    private ServletContext context = null;    public MyContextListener(){    }    //该方法在ServletContext启动之后被调用,并准备好处理客户端请求    @Override    public void contextInitialized(ServletContextEvent servletContextEvent) {        this.context = servletContextEvent.getServletContext();        //通过自己实现的逻辑并将结果记录在属性中        context = setAttribute("myData","this is myData");    }    @Override    public void contextDestroyed(ServletContextEvent servletContextEvent) {        this.context = null;    }}

(2)注册监听器。

在web.xml文件中需要注册自定义的监听器。

com.joe.controller.MyContextListener

(3) 测试。

一旦Web应用启动的时候,我们就能在任意的Servlet或者JSP中通过下面的方式获取我们初始化的参数,如下:

String myData = (String)getServletContext().getAttribute("myData");

Spring中的ContextLoaderListener

分析了ServletContextListener的使用方式后再来分析Spring中的ContextLoaderListener的实现就容易得多了,虽然ContextLoaderListener实现的逻辑要复杂的多,但是大致的套路还是万变不离其宗。

ServletContext启动之后会调用ServletContextListener的contextInitialized方法,那么,我们就从这个函数开始分析。

public void contextInitialized(ServletContextEvent event) {        initWebApplicationContext(event.getServletContext());    }

这里涉及了一个常用类WebApplicationContext:在Web应用中,我们会用到WebApplicationContext,WebApplicationContext继承自ApplicationContext,在ApplicationContext的基础上又追加了一些特定于Web的操作及属性,非常类似于我们通过编程方式使用Spring时使用的ClassPathXmlApplicationContext类提供的功能。继续跟踪代码:

public WebApplicationContext initWebApplicationContext(ServletContext servletContext) {        if (servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE) != null) {            throw new IllegalStateException(                    //web.xml中存在多次ContextLoader定义                    "Cannot initialize context because there is already a root application context present - " +                    "check whether you have multiple ContextLoader* definitions in your web.xml!");        }        servletContext.log("Initializing Spring root WebApplicationContext");        Log logger = LogFactory.getLog(ContextLoader.class);        if (logger.isInfoEnabled()) {            logger.info("Root WebApplicationContext: initialization started");        }        long startTime = System.currentTimeMillis();        try {            if (this.context == null) {                //初始化context                this.context = createWebApplicationContext(servletContext);            }            if (this.context instanceof ConfigurableWebApplicationContext) {                ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) this.context;                if (!cwac.isActive()) {                    // The context has not yet been refreshed -> provide services such as                    // setting the parent context, setting the application context id, etc                    if (cwac.getParent() == null) {                        // The context instance was injected without an explicit parent ->                        // determine parent for root web application context, if any.                        ApplicationContext parent = loadParentContext(servletContext);                        cwac.setParent(parent);                    }                    configureAndRefreshWebApplicationContext(cwac, servletContext);                }            }            //记录在servletContext            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.isInfoEnabled()) {                long elapsedTime = System.currentTimeMillis() - startTime;                logger.info("Root WebApplicationContext initialized in " + elapsedTime + " ms");            }            return this.context;        }        catch (RuntimeException | Error ex) {            logger.error("Context initialization failed", ex);            servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ex);            throw ex;        }    }

上述函数主要体现了创建WebApplicationContext实例的一个功能架构,从函数中我们看到了初始化的大致步骤:

(1)WebApplicationContext存在性的验证。

  在配置中只允许声明一次ServletContextListener,多次声明会扰乱Spring的执行逻辑,所以在这里先做的就是对此验证,在Spring中如果创建WebApplicationContext实例会记录在ServletContext中以方便全局调用,而使用的key就是WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE,所以验证的方式是查看ServletContext实例中是否有对应key的属性。

(2)创建WebApplicationContext的实例。

  如果通过验证,则Spring将创建WebApplicationContext实例的工作委托给了createWebApplicationContext函数:

protected WebApplicationContext createWebApplicationContext(ServletContext sc) {        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) { 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 { 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); } } }

在contextLoader类中有这样的静态代码块:

static {        // Load default strategy implementations from properties file.        // This is currently strictly internal and not meant to be customized        // by application developers.        try {            ClassPathResource resource = new ClassPathResource(DEFAULT_STRATEGIES_PATH, ContextLoader.class);            defaultStrategies = PropertiesLoaderUtils.loadProperties(resource);        }        catch (IOException ex) {            throw new IllegalStateException("Could not load 'ContextLoader.properties': " + ex.getMessage());        }    }

根据以上静态代码块的内容,我们推断在当前类ContextLoader同样目录下必定会存在属性文件ContextLoader.properties,查看后果然存在,内容如下:

org.springframework.web.context.WebApplicationContext=org.springframework.web.context.support.XmlWebApplicationContext

综合以上的代码分析,在初始化的过程中,程序首先会读取ContextLoader类的同目录下的属性文件ContextLoader.properties,并根据其中的配置读取将要实现WebApplicationContext接口的实现类,并根据这个实现类通过反射的方式进行实例的创建。

(3)将实例记录在servletContext中。

(4)映射当前的类加载器与创建的实例到全局变量currentContextPerThread中。

 参考:《Spring源码深度解析》 郝佳 编著:

转载于:https://www.cnblogs.com/Joe-Go/p/10297948.html

你可能感兴趣的文章
P3384 【模板】树链剖分
查看>>
Thrift源码分析(二)-- 协议和编解码
查看>>
考勤系统之计算工作小时数
查看>>
4.1 分解条件式
查看>>
Equivalent Strings
查看>>
收藏其他博客园主写的代码,学习加自用。先表示感谢!!!
查看>>
H5 表单标签
查看>>
C语言编程-9_4 字符统计
查看>>
在webconfig中写好连接后,在程序中如何调用?
查看>>
限制用户不能删除SharePoint列表中的条目(项目)
查看>>
feign调用spring clound eureka 注册中心服务
查看>>
ZT:Linux上安装JDK,最准确
查看>>
LimeJS指南3
查看>>
关于C++ const成员的一些细节
查看>>
《代码大全》学习摘要(五)软件构建中的设计(下)
查看>>
C#检测驱动是否安装的问题
查看>>
web-4. 装饰页面的图像
查看>>
微信测试账户
查看>>
Android ListView上拉获取下一页
查看>>
算法练习题
查看>>