这里输入引用文本在Tomcat的
conf目录
下,有关于全局组件配置的server.xml
,有关于角色与用户配置的tomcat-users.xml
文件,有关于包内访问安全限制及自定义ClassLoader的catalina.properties
文件,还有一个用于做部署在此Tomcat内所有web应用的全局配置的web.xml
。 类似于面向对象编程中的父类
的概念。所有的应用都会将此文件中定义的信息包含,和应用程序自身的web.xml做一个类似merge的操作。
了解了以上信息之后,来看一下Tomcat内部是如何解析web.xml文件的。
web.xm组件加载顺序为:context-param -> listener -> filter -> servlet(同类则按编写顺序执行)。 tomcat启动时序图
解析web.xml的代码,位于ContextConfig类中:
Set<WebXml> defaults = new HashSet<>();
defaults.add(getDefaultWebXmlFragment());//首先是默认web.xml
WebXml webXml = createWebXml();
// Parse context level web.xml
InputSource contextWebXml = getContextWebXmlSource();
if (!webXmlParser.parseWebXml(contextWebXml, webXml, false)) {
ok = false;
}
再之后是Servlet3的新特性中的web-fragement特性。需要先解析已有jar包中是否包含自定义配置
/* Ordering is important here
Step 1. Identify all the JARs packaged with the application and those
provided by the container. If any of the application JARs have a
web-fragment.xml it will be parsed at this point. web-fragment.xml
files are ignored for container provided JARs.
*/
Map<String,WebXml> fragments = processJarsForWebFragments(webXml);
// Step 2. Order the fragments.
Set<WebXml> orderedFragments = null;
orderedFragments = WebXml.orderWebFragments(webXml, fragments, sContext);
之后则是把web-fragement.xml和web.xml合到一起。
/* Step 7. Apply global defaults
Have to merge defaults before JSP conversion since defaults
provide JSP servlet definition.
*/
webXml.merge(defaults); //merge全局web.xml,这里是先放进去,后续自定义的会覆盖
再向下走到merge应用自定义的web.xml中。
// Step 9. Apply merged web.xml to Context
if (ok) {
configureContext(webXml);
}