無聊在家看源碼,雖然沒看懂多少,但是還是想紀(jì)錄一下,埋下一顆種子。
有時(shí)候,一些問題,我總是想要追根尋底,一直搞的Web開發(fā),但是卻每次只能在Controller層去編寫代碼,調(diào)試代碼,感覺心里總有些(其實(shí)是很)不爽,所以擅自超出自己的能力范圍,去看了看Tomcat和Servlet和Spring的源碼,果然如我所料,的確是非常難,所以,只能記下一些關(guān)鍵點(diǎn),為以后留下點(diǎn)東西。
看了好久,直到最后,才發(fā)現(xiàn)這個(gè)關(guān)鍵點(diǎn),如下圖所示。

發(fā)現(xiàn)沒有,這里是三個(gè)包之間的交互點(diǎn),從這三條堆棧的運(yùn)行來看,就可以看到這三個(gè)關(guān)鍵點(diǎn)之間是如何交互的。
那么一個(gè)一個(gè)函數(shù)來看。
private synchronized void initServlet(Servlet servlet) throws ServletException {
if(!this.instanceInitialized || this.singleThreadModel) {
try {
this.instanceSupport.fireInstanceEvent("beforeInit", servlet);
if(Globals.IS_SECURITY_ENABLED) {
boolean f = false;
try {
Object[] args = new Object[]{this.facade};
SecurityUtil.doAsPrivilege("init", servlet, classType, args);
f = true;
} finally {
if(!f) {
SecurityUtil.remove(servlet);
}
}
} else {
servlet.init(this.facade);
}
this.instanceInitialized = true;
this.instanceSupport.fireInstanceEvent("afterInit", servlet);
} catch (UnavailableException var10) {
this.instanceSupport.fireInstanceEvent("afterInit", servlet, var10);
this.unavailable(var10);
throw var10;
} catch (ServletException var11) {
this.instanceSupport.fireInstanceEvent("afterInit", servlet, var11);
throw var11;
} catch (Throwable var12) {
ExceptionUtils.handleThrowable(var12);
this.getServletContext().log("StandardWrapper.Throwable", var12);
this.instanceSupport.fireInstanceEvent("afterInit", servlet, var12);
throw new ServletException(sm.getString("standardWrapper.initException", new Object[]{this.getName()}), var12);
}
}
}
這個(gè)就是Tomcat的那條堆棧的函數(shù)??吹胶芏?code>blog都很空泛的說,Web容器會加載web.xml的內(nèi)容,然后加載里面定義的Servlet,之后會調(diào)用init()的內(nèi)容,但是都沒有代碼級別的示例,這讓我著實(shí)心癢。所以想盡辦法來窺的一絲一毫。
這里函數(shù)里面其實(shí)已經(jīng)加載好了Servlet,如果在Idea里面把鼠標(biāo)移動到Servlet上面可以看到類型就是我在web.xml里面配置的DispatherServlet的實(shí)例。
關(guān)鍵代碼就是Servlet.init(this.facade)。也就是這里Tomcat調(diào)用Servlet的init()函數(shù)。這邊也應(yīng)該要注意到的是參數(shù)this.facade,沒錯,這個(gè)就是Servlet接口中的init(ServletConfig config)的config參數(shù),里面最重要的就是給了Servlet一個(gè)ServletContext的引用,這樣每個(gè)Servlet就可以訪問到唯一的一個(gè)ServletContext。
下面的是Servlet的接口源代碼。
package javax.servlet;
import java.io.IOException;
import java.io.Serializable;
import java.util.Enumeration;
import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public abstract class GenericServlet implements Servlet, ServletConfig, Serializable {
private static final long serialVersionUID = 1L;
private transient ServletConfig config;
public GenericServlet() {
}
public void destroy() {
}
public ServletConfig getServletConfig() {
return this.config;
}
public ServletContext getServletContext() {
return this.getServletConfig().getServletContext();
}
public String getServletInfo() {
return "";
}
public void init(ServletConfig config) throws ServletException {
this.config = config;
this.init();
}
public void init() throws ServletException {
}
public abstract void service(ServletRequest var1, ServletResponse var2) throws ServletException, IOException;
}
從接口中可以更加明顯的看到config賦值行為。之后又接著調(diào)用了沒有參數(shù)的init()函數(shù)。之后就是Spring的有個(gè)HttpServletBean的類進(jìn)行了init()函數(shù)的實(shí)現(xiàn)。具體源代碼如下。
public final void init() throws ServletException {
if(this.logger.isDebugEnabled()) {
this.logger.debug("Initializing servlet \'" + this.getServletName() + "\'");
}
try {
HttpServletBean.ServletConfigPropertyValues ex = new HttpServletBean.ServletConfigPropertyValues(this.getServletConfig(), this.requiredProperties);
BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(this);
ServletContextResourceLoader resourceLoader = new ServletContextResourceLoader(this.getServletContext());
bw.registerCustomEditor(Resource.class, new ResourceEditor(resourceLoader, this.getEnvironment()));
this.initBeanWrapper(bw);
bw.setPropertyValues(ex, true);
} catch (BeansException var4) {
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");
}
}
從這個(gè)函數(shù)開始就沒有Tomcat的什么事情了,就開始進(jìn)入到Spring的管理中來了。
好的,下面雖然看的不是很懂了,但是能走幾步就走幾步。
按照調(diào)用棧的過程,可以看到之后是FrameworkServlet的initServletBean的調(diào)用。這回先上代碼。
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 {
//開始初始化前端控制器自己的Bean容器
this.webApplicationContext = this.initWebApplicationContext();
this.initFrameworkServlet();
} catch (ServletException var5) {
this.logger.error("Context initialization failed", var5);
throw var5;
} catch (RuntimeException var6) {
this.logger.error("Context initialization failed", var6);
throw var6;
}
if(this.logger.isInfoEnabled()) {
long elapsedTime = System.currentTimeMillis() - startTime;
this.logger.info("FrameworkServlet \'" + this.getServletName() + "\': initialization completed in " + elapsedTime + " ms");
}
}
從代碼中可以看到最先做的事情是初始化了DispatherServlet自己的Bean容器,好,在進(jìn)入這個(gè)初始的代碼看看,又做了一些什么事情呢。
protected WebApplicationContext initWebApplicationContext() {
//先嘗試從ServletContext中獲得全局的Spring容器
//全局的Spring容器是通過監(jiān)聽器獲得的,但是我這里沒有配置
//所以返回的是個(gè)null,rootContext=null
WebApplicationContext rootContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
WebApplicationContext wac = null;
//分為兩種情況,一種是Bean容器已存在(什么情況下會這樣呢?)
if(this.webApplicationContext != null) {
wac = this.webApplicationContext;
if(wac instanceof ConfigurableWebApplicationContext) {
ConfigurableWebApplicationContext attrName = (ConfigurableWebApplicationContext)wac;
if(!attrName.isActive()) {
if(attrName.getParent() == null) {
attrName.setParent(rootContext);
}
//最后調(diào)用這個(gè)配置和刷新Bean容器
//如果是下面一個(gè)創(chuàng)建的分支的話,最后也是會執(zhí)行這個(gè)函數(shù)的
this.configureAndRefreshWebApplicationContext(attrName);
}
}
}
//如果沒有初始化,第一次進(jìn)來的時(shí)候一定是沒有初始化的
//找一下?怎么找?
if(wac == null) {
wac = this.findWebApplicationContext();
}
//找不到就造一個(gè),實(shí)例化一個(gè)
if(wac == null) {
wac = this.createWebApplicationContext(rootContext);
}
if(!this.refreshEventReceived) {
this.onRefresh(wac);
}
if(this.publishContext) {
String attrName1 = this.getServletContextAttributeName();
this.getServletContext().setAttribute(attrName1, wac);
if(this.logger.isDebugEnabled()) {
this.logger.debug("Published WebApplicationContext of servlet \'" + this.getServletName() + "\' as ServletContext attribute with name [" + attrName1 + "]");
}
}
return wac;
}
在走兩步到FrameServlet的createWebApplicationContext這里。有個(gè)關(guān)鍵一個(gè)是把從ServletContext中獲得原始的Bean容器作為了DispatherServlet自己的父容器了。
protected WebApplicationContext createWebApplicationContext(ApplicationContext parent) {
Class contextClass = this.getContextClass();
if(this.logger.isDebugEnabled()) {
this.logger.debug("Servlet with name \'" + this.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 \'" + this.getServletName() + "\': custom WebApplicationContext class [" + contextClass.getName() + "] is not of type ConfigurableWebApplicationContext");
} else {
ConfigurableWebApplicationContext wac = (ConfigurableWebApplicationContext)BeanUtils.instantiateClass(contextClass);
wac.setEnvironment(this.getEnvironment());
//將從監(jiān)聽器獲得的Spring容器作為父容器
wac.setParent(parent);
wac.setConfigLocation(this.getContextConfigLocation());
//調(diào)用這個(gè)配置和刷新Web應(yīng)用上下文的函數(shù)
this.configureAndRefreshWebApplicationContext(wac);
return wac;
}
}
好,接著看。
protected void configureAndRefreshWebApplicationContext(ConfigurableWebApplicationContext wac) {
if(ObjectUtils.identityToString(wac).equals(wac.getId())) {
if(this.contextId != null) {
wac.setId(this.contextId);
} else {
wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX + ObjectUtils.getDisplayString(this.getServletContext().getContextPath()) + "/" + this.getServletName());
}
}
wac.setServletContext(this.getServletContext());
wac.setServletConfig(this.getServletConfig());
wac.setNamespace(this.getNamespace());
wac.addApplicationListener(new SourceFilteringListener(wac, new FrameworkServlet.ContextRefreshListener(null)));
ConfigurableEnvironment env = wac.getEnvironment();
if(env instanceof ConfigurableWebEnvironment) {
((ConfigurableWebEnvironment)env).initPropertySources(this.getServletContext(), this.getServletConfig());
}
this.postProcessWebApplicationContext(wac);
this.applyInitializers(wac);
//上面都是把一些ServletContext和ServletConfig之類的設(shè)置進(jìn)入Web應(yīng)用上下,下面是refresh()
wac.refresh();
}
再進(jìn)入到refresh()函數(shù)中,md,完全沒看懂,逃...
public void refresh() throws BeansException, IllegalStateException {
Object var1 = this.startupShutdownMonitor;
synchronized(this.startupShutdownMonitor) {
this.prepareRefresh();
ConfigurableListableBeanFactory beanFactory = this.obtainFreshBeanFactory();
this.prepareBeanFactory(beanFactory);
try {
this.postProcessBeanFactory(beanFactory);
this.invokeBeanFactoryPostProcessors(beanFactory);
this.registerBeanPostProcessors(beanFactory);
this.initMessageSource();
this.initApplicationEventMulticaster();
this.onRefresh();
this.registerListeners();
this.finishBeanFactoryInitialization(beanFactory);
//以上都不知道在干啥了
this.finishRefresh();
} catch (BeansException var5) {
this.destroyBeans();
this.cancelRefresh(var5);
throw var5;
}
}
}
中間跳過無數(shù)看不懂的東西,好像是一些事件傳遞,監(jiān)聽,委托之類的,最后終于調(diào)用了DispatherServlet的onRefresh函數(shù)和initStrategies函數(shù)。但是其實(shí)在DispatherServlet被Tomcat初始化的時(shí)候會先調(diào)用DiapatherServlet的靜態(tài)區(qū)塊,之后才是無參構(gòu)造函數(shù)。
protected void onRefresh(ApplicationContext context) {
this.initStrategies(context);
}
protected void initStrategies(ApplicationContext context) {
this.initMultipartResolver(context);
this.initLocaleResolver(context);
this.initThemeResolver(context);
this.initHandlerMappings(context);
this.initHandlerAdapters(context);
this.initHandlerExceptionResolvers(context);
this.initRequestToViewNameTranslator(context);
this.initViewResolvers(context);
this.initFlashMapManager(context);
}
再補(bǔ)上我這個(gè)Debug項(xiàng)目的web.xml文件。
<?xml version="1.0" encoding="UTF-8" ?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<servlet>
<servlet-name>spitter</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--<init-param>-->
<!--<param-name>spring</param-name>-->
<!--<param-value>classpath:/spring/demo_produce.xml</param-value>-->
<!--</init-param>-->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spitter</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>spitter</servlet-name>
<url-pattern>*.service</url-pattern>
</servlet-mapping>
</web-app>
以及本次的Debug的環(huán)境是Tomcat8.0和Spring4.0.6版本,不同的版本之間應(yīng)該會有一些出入,所以紀(jì)錄一下版本,想要調(diào)試的源代碼版本是Github上面的AllDemo的demo_producer的612dd1316d4d762c166901698ba1818f1b18bfca版本。
還得補(bǔ)一張完整堆棧圖。

看了那么多,小結(jié)一下,DispatcherServlet繼承了FrameWorkServlet,這個(gè)類里面其實(shí)幫助初始化了Web上下文,最后才是核心控制器的東西。