广告
返回顶部
首页 > 资讯 > 精选 >Spring MVC的原理是什么
  • 154
分享到

Spring MVC的原理是什么

2023-06-27 10:06:23 154人浏览 独家记忆
摘要

今天小编给大家分享一下spring mvc的原理是什么的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家参考一下,希望大家阅读完这篇文章后有所收获,下面我们一起来了解一下吧。springMVC是一种

今天小编给大家分享一下spring mvc的原理是什么的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家参考一下,希望大家阅读完这篇文章后有所收获,下面我们一起来了解一下吧。

springMVC是一种基于Spring实现了WEB MVC设计模式的请求驱动类型的轻量级Web框架,使用了MVC的架构模式思想,将Web层进行指责解耦,并管理应用所需的生命周期,为简化日常开发,提供了很大便利。

Spring MVC的原理是什么

1.简介

在上一篇文章中,我向大家介绍了 Spring MVC 是如何处理 Http 请求的。Spring MVC 可对外提供服务时,说明其已经处于了就绪状态。再次之前,Spring MVC 需要进行一系列的初始化操作。正所谓兵马未动,粮草先行。这些操作包括创建容器,加载 DispatcherServlet 中用到的各种组件等。本篇文章就来和大家讨论一下这些初始化操作中的容器创建操作,容器的创建是其他一些初始化过程的基础。那其他的就不多说了,我们直入主题吧。

2.容器的创建过程

一般情况下,我们会在一个 Web 应用中配置两个容器。一个容器用于加载 Web 层的类,比如我们的接口 Controller、HandlerMapping、ViewResolver 等。在本文中,我们把这个容器叫做 web 容器。另一个容器用于加载业务逻辑相关的类,比如 service、dao 层的一些类。在本文中,我们把这个容器叫做业务容器。在容器初始化的过程中,业务容器会先于 web 容器进行初始化。web 容器初始化时,会将业务容器作为父容器。这样做的原因是,web 容器中的一些 bean 会依赖于业务容器中的 bean。比如我们的 controller 层接口通常会依赖 service 层的业务逻辑类。

下面举个例子进行说明:

我们将 dao 层的类配置在 application-dao.xml 文件中,将 service 层的类配置在 application-service.xml 文件中。然后我们将这两个配置文件通过 标签导入到 application.xml 文件中。此时,我们可以让业务容器去加载 application.xml 配置文件即可。另一方面,我们将 Web 相关的配置放在 application-web.xml 文件中,并将该文件交给 Web 容器去加载。

这里我们把配置文件进行分层,结构上看起来清晰了很多,也便于维护。这个其实和代码分层是一个道理,如果我们把所有的代码都放在同一个包下,那看起来会多难受啊。同理,我们用业务容器和 Web 容器去加载不同的类也是一种分层的体现吧。当然,如果应用比较简单,仅用 Web 容器去加载所有的类也不是不可以。

2.1 业务容器的创建过程

前面说了一些背景知识作为铺垫,那下面我们开始分析容器的创建过程吧。按照创建顺序,我们先来分析业务容器的创建过程。业务容器的创建入口是 ContextLoaderListener 的 contextInitialized 方法。顾名思义,ContextLoaderListener 是用来监听 ServletContext 加载事件的。当 ServletContext 被加载后,监听器的 contextInitialized 方法就会被 Servlet 容器调用。ContextLoaderListener Spring 框架提供的,它的配置方法如下:

org.springframework.web.context.ContextLoaderListenercontextConfigLocationclasspath:application.xml

如上,ContextLoaderListener 可通过 ServletContext 获取到 contextConfigLocation 配置。这样,业务容器就可以加载 application.xml 配置文件了。那下面我们来分析一下 ContextLoaderListener 的源码吧。

public class ContextLoaderListener extends ContextLoader implements ServletContextListener {// 省略部分代码@Overridepublic void contextInitialized(ServletContextEvent event) {// 初始化 WebApplicationContextinitWebApplicationContext(event.getServletContext());}}public WebApplicationContext initWebApplicationContext(ServletContext servletContext) {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()) {...}long startTime = System.currentTimeMillis();try {if (this.context == null) {// 创建 WebApplicationContextthis.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);}// 配置并刷新 WebApplicationContextconfigureAndRefreshWebApplicationContext(cwac, servletContext);}}// 设置 ApplicationContext 到 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.isDebugEnabled()) {...}if (logger.isInfoEnabled()) {...}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;}}

如上,我们看一下上面的创建过程。首先 Spring 会检测 ServletContext 中 ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE 属性有没有被设置,若被设置过,则抛出异常。若未设置,则调用 createWebApplicationContext 方法创建容器。创建好后,再调用 configureAndRefreshWebApplicationContext 方法配置并刷新容器。最后,调用 setAttribute 方法将容器设置到 ServletContext 中。经过以上几步,整个创建流程就结束了。流程并不复杂,可简单总结为创建容器 → 配置并刷新容器 → 设置容器到 ServletContext 中。这三步流程中,最后一步就不进行分析,接下来分析一下第一步和第二步流程对应的源码。如下:

protected WebApplicationContext createWebApplicationContext(ServletContext sc) {// 判断创建什么类型的容器,默认类型为 XmlWebApplicationContextClass> 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);}}}

简单说一下 createWebApplicationContext 方法的流程,该方法首先会调用 determineContextClass 判断创建什么类型的容器,默认为 XmlWebApplicationContext。然后调用 instantiateClass 方法通过反射的方式创建容器实例。instantiateClass 方法就不跟进去分析了,大家可以自己去看看,比较简单。

继续往下分析,接下来分析一下 configureAndRefreshWebApplicationContext 方法的源码。如下:

protected void configureAndRefreshWebApplicationContext(ConfigurableWebApplicationContext wac, ServletContext sc) {if (ObjectUtils.identityToString(wac).equals(wac.getId())) {// 从 ServletContext 中获取用户配置的 contextId 属性String idParam = sc.getInitParameter(CONTEXT_ID_PARAM);if (idParam != null) {// 设置容器 idwac.setId(idParam);}else {// 用户未配置 contextId,则设置一个默认的容器 idwac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX +ObjectUtils.getDisplayString(sc.getContextPath()));}}wac.setServletContext(sc);// 获取 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();}

上面的源码不是很长,逻辑不是很复杂。下面简单总结 configureAndRefreshWebApplicationContext 方法主要做了事情,如下:

设置容器 id 获取 contextConfigLocation 配置,并设置到容器中 刷新容器 到此,关于业务容器的创建过程就分析完了,下面我们继续分析 Web 容器的创建过程。

2.2 Web 容器的创建过程

前面说了业务容器的创建过程,业务容器是通过 ContextLoaderListener。那 Web 容器是通过什么创建的呢?答案是通过 DispatcherServlet。我在上一篇文章介绍 httpservletBean 抽象类时,说过该类覆写了父类 HttpServlet 中的 init 方法。这个方法就是创建 Web 容器的入口,那下面我们就从这个方法入手。如下:

// -☆- org.springframework.web.servlet.HttpServletBeanpublic final void init() throws ServletException {if (logger.isDebugEnabled()) {...}// 获取 ServletConfig 中的配置信息PropertyValues pvs = new ServletConfigPropertyValues(getServletConfig(), this.requiredProperties);if (!pvs.isEmpty()) {try {BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(this);ResourceLoader resourceLoader = new ServletContextResourceLoader(getServletContext());bw.reGISterCustomEditor(Resource.class, new ResourceEditor(resourceLoader, getEnvironment()));initBeanWrapper(bw);// 设置配置信息到目标对象中bw.setPropertyValues(pvs, true);}catch (BeansException ex) {if (logger.isErrorEnabled()) {...}throw ex;}}// 进行后续的初始化initServletBean();if (logger.isDebugEnabled()) {...}}protected void initServletBean() throws ServletException {}

上面的源码主要做的事情是将 ServletConfig 中的配置信息设置到 HttpServletBean 的子类对象中(比如 DispatcherServlet),我们并未从上面的源码中发现创建容器的痕迹。不过如果大家注意看源码的话,会发现 initServletBean 这个方法稍显奇怪,是个空方法。这个方法的访问级别为 protected,子类可进行覆盖。HttpServletBean 子类 FrameworkServlet 覆写了这个方法,下面我们到 FrameworkServlet 中探索一番。

// -☆- org.springframework.web.servlet.FrameworkServletprotected final void initServletBean() throws ServletException {getServletContext().log("Initializing Spring FrameworkServlet '" + getServletName() + "'");if (this.logger.isInfoEnabled()) {...}long startTime = System.currentTimeMillis();try {// 初始化容器this.webApplicationContext = initWebApplicationContext();initFrameworkServlet();}catch (ServletException ex) {this.logger.error("Context initialization failed", ex);throw ex;}catch (RuntimeException ex) {this.logger.error("Context initialization failed", ex);throw ex;}if (this.logger.isInfoEnabled()) {...}}protected WebApplicationContext initWebApplicationContext() {// 从 ServletContext 中获取容器,也就是 ContextLoaderListener 创建的容器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) {// 设置 rootContext 为父容器cwac.setParent(rootContext);}// 配置并刷新容器configureAndRefreshWebApplicationContext(cwac);}}}if (wac == null) {// 尝试从 ServletContext 中获取容器wac = findWebApplicationContext();}if (wac == null) {// 创建容器,并将 rootContext 作为父容器wac = createWebApplicationContext(rootContext);}if (!this.refreshEventReceived) {onRefresh(wac);}if (this.publishContext) {String attrName = getServletContextAttributeName();// 将创建好的容器设置到 ServletContext 中getServletContext().setAttribute(attrName, wac);if (this.logger.isDebugEnabled()) {...}}return wac;}protected WebApplicationContext createWebApplicationContext(ApplicationContext parent) {// 获取容器类型,默认为 XmlWebApplicationContext.classClass> contextClass = getContextClass();if (this.logger.isDebugEnabled()) {...}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());wac.setParent(parent);wac.setConfigLocation(getContextConfigLocation());// 配置并刷新容器configureAndRefreshWebApplicationContext(wac);return wac;}protected void configureAndRefreshWebApplicationContext(ConfigurableWebApplicationContext wac) {if (ObjectUtils.identityToString(wac).equals(wac.getId())) {// 设置容器 idif (this.contextId != null) {wac.setId(this.contextId);}else {// 生成默认 idwac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX +ObjectUtils.getDisplayString(getServletContext().getContextPath()) + '/' + getServletName());}}wac.setServletContext(getServletContext());wac.setServletConfig(getServletConfig());wac.setNamespace(getNamespace());wac.addApplicationListener(new SourceFilteringListener(wac, new ContextRefreshListener()));ConfigurableEnvironment env = wac.getEnvironment();if (env instanceof ConfigurableWebEnvironment) {((ConfigurableWebEnvironment) env).initPropertySources(getServletContext(), getServletConfig());}// 后置处理,子类可以覆盖进行一些自定义操作。在 Spring MVC 未使用到,是个空方法。postProcessWebApplicationContext(wac);applyInitializers(wac);// 刷新容器wac.refresh();}

以上就是创建 Web 容器的源码,下面总结一下该容器创建的过程。如下:

从 ServletContext 中获取 ContextLoaderListener 创建的容器 若 this.webApplicationContext != null 条件成立,仅设置父容器和刷新容器即可 尝试从 ServletContext 中获取容器,若容器不为空,则无需执行步骤4 创建容器,并将 rootContext 作为父容器 设置容器到 ServletContext 中 到这里,关于 Web 容器的创建过程就讲完了。总的来说,Web 容器的创建过程和业务容器的创建过程大致相同,但是差异也是有的,不能忽略。

以上就是“Spring MVC的原理是什么”这篇文章的所有内容,感谢各位的阅读!相信大家阅读完这篇文章都有很大的收获,小编每天都会为大家更新不同的知识,如果还想学习更多的知识,请关注编程网精选频道。

--结束END--

本文标题: Spring MVC的原理是什么

本文链接: https://www.lsjlt.com/news/309982.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • Spring MVC的原理是什么
    今天小编给大家分享一下Spring MVC的原理是什么的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家参考一下,希望大家阅读完这篇文章后有所收获,下面我们一起来了解一下吧。SpringMVC是一种...
    99+
    2023-06-27
  • Spring MVC原理是什么
    这篇文章将为大家详细讲解有关Spring MVC原理是什么,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。springMVC,是spring的一个子框架,当然拥有spring的特性,如依赖注入。在web模型...
    99+
    2023-06-27
  • tomcat+spring mvc原理是什么
    这篇文章主要讲解了“tomcat+spring mvc原理是什么”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“tomcat+spring mvc原理是什么”吧!tomat + spring ...
    99+
    2023-06-02
  • Spring MVC异常解析器的原理是什么
    本篇内容主要讲解“Spring MVC异常解析器的原理是什么”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“Spring MVC异常解析器的原理是什么”吧!使用介...
    99+
    2022-10-19
  • 在Spring mvc中实现DispatchServlet的原理是什么
    在Spring mvc中实现DispatchServlet的原理是什么?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。在Spring中, ContextLoaderListene...
    99+
    2023-05-31
    springmvc hs dispatchservlet
  • spring mvc是什么
    spring mvc是一个基于Java的开源Web应用程序框架,提供了一种模型,视图,控制器架构模式来构建灵活、可扩展的Web应用程序。无论是大型企业级应用程序还是小型个人项目,spring mvc都是一个理想的选择,其模块化设计和松耦合的...
    99+
    2023-08-09
  • Spring mvc中内置编码过滤器的原理是什么
    Spring mvc中内置编码过滤器的原理是什么?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。web.xml 中 添加如下配置:<filter> ...
    99+
    2023-05-31
    springmvc 滤器
  • Spring MVC的处理流程是什么
    本篇内容介绍了“Spring MVC的处理流程是什么”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!1、曾经的王者&mdash;&am...
    99+
    2023-06-15
  • spring、spring MVC和spring Boot是什么
    这篇文章主要介绍“spring、spring MVC和spring Boot是什么”,在日常操作中,相信很多人在spring、spring MVC和spring Boot是什么问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希...
    99+
    2023-06-05
  • Spring MVC能响应HTTP请求的原因是什么
    Spring MVC能响应HTTP请求的原因是什么,相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。很多Java面试官喜欢问这个问题:一个Spring MVC的项目文件里,开发人员...
    99+
    2023-06-02
  • spring session的原理是什么
    Spring Session是一种用于管理用户会话的框架,它通过将会话数据存储在外部存储介质中,而不是默认的内存中,来实现会话的持久...
    99+
    2023-09-21
    spring
  • spring scope的原理是什么
    Spring的Bean的作用域(scope)指定了一个Bean的实例是如何被创建和管理的。Spring框架提供了多种作用域,包括si...
    99+
    2023-08-31
    spring scope
  • ASP.NET MVC 2.0框架的原理是什么
    ASP.NET MVC 2.0框架的原理是什么,相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。使用微软VS工具开发Web应用程序主要有两种方式:一种是常用的创建ASP.NET W...
    99+
    2023-06-17
  • Spring框架的原理是什么
    这篇文章主要讲解了“Spring框架的原理是什么”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“Spring框架的原理是什么”吧!简要介绍spring的原理,并结合一个简单的实例,如何配置使用...
    99+
    2023-06-03
  • Spring中Spring Boot与Spring MVC的核心概念是什么
    这篇文章主要介绍了Spring中Spring Boot与Spring MVC的核心概念是什么的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇Spring中Spring Boot与Sp...
    99+
    2023-06-29
  • Spring底层原理是什么
    这篇文章主要讲解了“Spring底层原理是什么”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“Spring底层原理是什么”吧!Spring简介ClassPathXmlApplicationCo...
    99+
    2023-07-05
  • Spring Boot启动的原理是什么
    本文小编为大家详细介绍“Spring Boot启动的原理是什么”,内容详细,步骤清晰,细节处理妥当,希望这篇“Spring Boot启动的原理是什么”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起...
    99+
    2022-10-19
  • Spring Boot的底层原理是什么
    这篇文章主要讲解了“Spring Boot的底层原理是什么”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“Spring Boot的底层原理是什么”吧!1.基于你对springboot的理解描述...
    99+
    2023-06-27
  • Spring Boot的运行原理是什么
    本篇内容介绍了“Spring Boot的运行原理是什么”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!导读Spring Boot方式的项目开发...
    99+
    2023-06-02
  • Spring的工作原理是什么呢
    Spring的工作原理是什么呢,很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。Spring 的骨骼架构Spring 总共有十几个组件,但是真正核心的组件只有几个,...
    99+
    2023-06-02
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作