SpringMVC中的DispatcherServlet結(jié)構(gòu)和初始化詳解
前言
SpringMVC中Spring容器的關(guān)系是通過監(jiān)聽方式啟動(dòng)的。
那么Spring(或者說SpringMVC)與Servlet的Web容器(如:Tomcat、jetty)的關(guān)系則是通過DispatcherServlet進(jìn)行關(guān)聯(lián)。
在Web容器看,DispatcherServlet就是同一普通的Servlet,從Spring看是與Web的關(guān)聯(lián),會(huì)將所有的請(qǐng)求轉(zhuǎn)發(fā)到該控制器。
1、DispatcherServlet結(jié)構(gòu)

從層級(jí)能看出其頂層實(shí)現(xiàn)了Servlet和ServletConfig接口,由于Web容器只認(rèn)識(shí)Servlet,而Spring只認(rèn)識(shí)Bean,所以DispatcherServlet既是請(qǐng)求轉(zhuǎn)發(fā)和返回視圖解析控制中心,更是web與Spring的適配器,從其父子結(jié)構(gòu)層級(jí)就能看出,慢慢的從Servlet適配到Bean的過程。
1)、GenericServlet
GenericServlet實(shí)現(xiàn)了Servlet、ServletConfig接口,也實(shí)現(xiàn)了所有未實(shí)現(xiàn)的方法。主要是config相關(guān),init和service方法。
2)、HttpServlet
HttpServlet主要定義了Http協(xié)議相關(guān)的請(qǐng)求方法,以及Last-Modified和If-Modified-Since相關(guān)參數(shù)的處理。
3)、HttpServletBean
HttpServletBean除了繼承自HttpServlet,還實(shí)現(xiàn)了EnvironmentCapable和EnvironmentAware接口,處理Spring Environment相關(guān),之前分析過。
4)、FrameworkServlet
FrameworkServlet實(shí)現(xiàn)了接口ApplicationContextAware,注入了ApplicationContext,以及contextConfigLocation配置。
5)、DispatcherServlet
DispatcherServlet作為整個(gè)MVC的控制器,那么請(qǐng)求該轉(zhuǎn)發(fā)到哪個(gè)Controller,返回的model會(huì)該使用哪個(gè)視圖返回(視圖解析器進(jìn)行解析)。
都需要在這里進(jìn)行完成,所以初始化時(shí)需要使用到Spring MVC的九大件。
初始化時(shí)使用了策略模式初始化九大件
2、DispatcherServlet初始化(九大件的加載和初始化)
web容器啟動(dòng)時(shí)會(huì)加載配置的DispatcherServlet,則會(huì)調(diào)用其init方法,在GenericServlet中實(shí)現(xiàn),如下:
@Override
public void init(ServletConfig config) throws ServletException {
this.config = config;
this.init();
}設(shè)置了ServletConfig值,并且調(diào)用了自定義無(wú)參空方法init,在子類HttpServletBean中實(shí)現(xiàn)。
public final void init() throws ServletException {
// 解析init-param參數(shù),并封裝成ServletConfigPropertyValues
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) {
throw ex;
}
}
// Let subclasses do whatever initialization they like.
initServletBean();
}在初始化方法之前,允許init-param通過addRequiredProperty方法添加到requiredProperties屬性中的配置,以Bean的形式進(jìn)行加載。主要的方法初始化方法是調(diào)用本類的空方法initServletBean,在下層子類FrameworkServlet中實(shí)現(xiàn)
@Override
protected final void initServletBean() throws ServletException {
// 省略日志打印和,try catch部分的代碼
this.webApplicationContext = initWebApplicationContext();
// 留給子類實(shí)現(xiàn),子類DispatcherServlet沒有進(jìn)行實(shí)現(xiàn)
initFrameworkServlet();
}protected WebApplicationContext initWebApplicationContext() {
WebApplicationContext rootContext =
WebApplicationContextUtils.getWebApplicationContext(getServletContext());
WebApplicationContext wac = null;
if (this.webApplicationContext != null) {
// A context instance was injected at construction time -> use it
wac = this.webApplicationContext;
if (wac instanceof ConfigurableWebApplicationContext) {
ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) wac;
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 -> set
// the root application context (if any; may be null) as the parent
cwac.setParent(rootContext);
}
configureAndRefreshWebApplicationContext(cwac);
}
}
}
if (wac == null) {
// No context instance was injected at construction time -> see if one
// has been registered in the servlet context. If one exists, it is assumed
// that the parent context (if any) has already been set and that the
// user has performed any initialization such as setting the context id
wac = findWebApplicationContext();
}
if (wac == null) {
// 確保Spring容器創(chuàng)建并且唯一,所以無(wú)論ContextLoaderListener是否啟動(dòng)和refresh
wac = createWebApplicationContext(rootContext);
}
if (!this.refreshEventReceived) {
// Either the context is not a ConfigurableApplicationContext with refresh
// support or the context injected at construction time had already been
// refreshed -> trigger initial onRefresh manually here.
synchronized (this.onRefreshMonitor) {
onRefresh(wac);
}
}
if (this.publishContext) {
// 將Spring的WebApplicationContext容器,設(shè)置到Web容器中
String attrName = getServletContextAttributeName();
getServletContext().setAttribute(attrName, wac);
}
return wac;
}無(wú)論監(jiān)聽是否啟動(dòng)Spring容器執(zhí)行refresh方法,這里都會(huì)進(jìn)行檢查啟動(dòng)。
并將啟動(dòng)的Spring容器,設(shè)置到web容器中,所以當(dāng)啟動(dòng)完成后兩個(gè)容器中就是你中有我,我中有你的狀態(tài)。
Spring MVC的初始化會(huì)同步鎖synchronized(onRefreshMonitor)保證下初始化,在子類層級(jí)DispatcherServlet中完成:
@Override
protected void onRefresh(ApplicationContext context) {
initStrategies(context);
}使用策略模式初始化九大件,為后續(xù)請(qǐng)求調(diào)用,視圖解析等做準(zhǔn)備。
protected void initStrategies(ApplicationContext context) {
// 文件上傳
initMultipartResolver(context);
// i18n相關(guān)解析器
initLocaleResolver(context);
// 主題解析器(一種主題就是一類網(wǎng)頁(yè)風(fēng)格)
initThemeResolver(context);
// 請(qǐng)求映射
initHandlerMappings(context);
// 適配器,后面請(qǐng)求轉(zhuǎn)發(fā)的Controller會(huì)專門分析
initHandlerAdapters(context);
// 操作異常的解析處理(中途發(fā)送異常該調(diào)整到哪里)
initHandlerExceptionResolvers(context);
// 請(qǐng)求的Controller沒有返回View時(shí),該如何解析
initRequestToViewNameTranslator(context);
// 視圖解析器(ModelAndView中的view字符串怎么進(jìn)行解析)
initViewResolvers(context);
// 請(qǐng)求屬性(參數(shù))管理器,主要用于重定向等情況時(shí)獲取屬性,比如post重定向到get
initFlashMapManager(context);
}九大件的處理方式大致相同,只是定義的Bean名稱和調(diào)用getBean的類型不同而已,比如上傳文件,如下:
private void initMultipartResolver(ApplicationContext context) {
// 省略日志打印和try catch的代碼
this.multipartResolver = context.getBean(MULTIPART_RESOLVER_BEAN_NAME, MultipartResolver.class);
}主要看初始化的什么類型,是在靜態(tài)代碼塊的策略模式中加載初始化(DispatcherServlet.properties),如下:
org.springframework.web.servlet.LocaleResolver=org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver org.springframework.web.servlet.ThemeResolver=org.springframework.web.servlet.theme.FixedThemeResolver org.springframework.web.servlet.HandlerMapping=org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping,\ org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping,\ org.springframework.web.servlet.function.support.RouterFunctionMapping org.springframework.web.servlet.HandlerAdapter=org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter,\ org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter,\ org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter,\ org.springframework.web.servlet.function.support.HandlerFunctionAdapter org.springframework.web.servlet.HandlerExceptionResolver=org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver,\ org.springframework.web.servlet.mvc.annotation.ResponseStatusExceptionResolver,\ org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver org.springframework.web.servlet.RequestToViewNameTranslator=org.springframework.web.servlet.view.DefaultRequestToViewNameTranslator org.springframework.web.servlet.ViewResolver=org.springframework.web.servlet.view.InternalResourceViewResolver org.springframework.web.servlet.FlashMapManager=org.springframework.web.servlet.support.SessionFlashMapManager
到此這篇關(guān)于SpringMVC中的DispatcherServlet結(jié)構(gòu)和初始化詳解的文章就介紹到這了,更多相關(guān)DispatcherServlet結(jié)構(gòu)和初始化內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
用Java打造簡(jiǎn)易計(jì)算器的實(shí)現(xiàn)步驟
這篇文章主要介紹了如何設(shè)計(jì)和實(shí)現(xiàn)一個(gè)簡(jiǎn)單的Java命令行計(jì)算器程序,該程序能夠執(zhí)行基本的數(shù)學(xué)運(yùn)算(加、減、乘、除),文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下2025-01-01
Java游戲開發(fā)之俄羅斯方塊的實(shí)現(xiàn)
俄羅斯方塊是一個(gè)最初由阿列克謝帕吉特諾夫在蘇聯(lián)設(shè)計(jì)和編程的益智類視頻游戲。本文和大家分享了利用Java語(yǔ)言實(shí)現(xiàn)這一經(jīng)典的小游戲的示例代碼,需要的可以參考一下2022-05-05
springboot實(shí)現(xiàn)rabbitmq的隊(duì)列初始化和綁定
這篇文章主要介紹了springboot實(shí)現(xiàn)rabbitmq的隊(duì)列初始化和綁定,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2018-10-10
logback的AsyncAppender高效日志處理方式源碼解析
這篇文章主要為大家介紹了logback的AsyncAppender高效日志處理方式源碼解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-10-10
mybatis實(shí)現(xiàn)表與對(duì)象的關(guān)聯(lián)關(guān)系_動(dòng)力節(jié)點(diǎn)Java學(xué)院整理
這篇文章主要介紹了mybatis實(shí)現(xiàn)表與對(duì)象的關(guān)聯(lián)關(guān)系_動(dòng)力節(jié)點(diǎn)Java學(xué)院整理,需要的朋友可以參考下2017-09-09
SpringBoot使用SpringDoc+OpenAPI3.0實(shí)現(xiàn)接口文檔自動(dòng)生成
本文介紹了在前后端分離項(xiàng)目中使用SpringDoc實(shí)現(xiàn)接口文檔自動(dòng)生成的方法,包括核心依賴、啟動(dòng)配置、常用注解、生產(chǎn)環(huán)境配置、帶Token權(quán)限接口調(diào)試等內(nèi)容,提高了接口文檔的生成效率和維護(hù)性,需要的朋友可以參考下2026-03-03

