背景。
tomcat 请求行和头解析完后,开始为该次请求找到负责人,即这个请求我要让那个应用来处理,找到那个应用后,还要找到我们的对接人Servlet,tomcat为了找到应用的对接人Servlet,通过了三级查找,才能最终定位到我们的Servlet
实现是由CoyoteAdapter的postParseRequest方法,具体逻辑是让Mapper来实现的,具体方法是internalMap,该方法先通过二分查找找到对应虚拟主机即Tomcat的host,再根据二分查找从host找到对应的context,最后根据context找servlet。
Host查找
tomcat 支持配置多个虚拟主机,默认的是host,如果配置了多个,tomcat是存在一个有序的MappedHost数组里,以便能通过二分查找快速的匹配
核心代码如下:
//MappedHost是一个有序数组,默认只有一个值即localhost
MappedHost[] hosts = this.hosts;
//通过二分查找一个一个比较host的name,找到对应的host
MappedHost mappedHost = exactFindIgnoreCase(hosts, host);
Context查找
contexts webapps目录下的应用名称,默认至少有doc,static,manager,host-manager,""(root),还有就是我们自己的应用名称,tomcat也是通过一个有序的数组MappedContext来存储对应的context
和查找host一样,也是通过二分查找,根据context path来比较,核心代码如下:
ContextList contextList = mappedHost.contextList;
//Host下面对应的context的有序数组
MappedContext[] contexts = contextList.contexts;
//二分查找
int pos = find(contexts, uri);
if (pos == -1) {
return;
}
int lastSlash = -1;
int uriEnd = uri.getEnd();
int length = -1;
boolean found = false;
MappedContext context = null;
while (pos >= 0) {
//找到对应的context
context = contexts[pos];
if (uri.startsWith(context.name)) {
length = context.name.length();
//tomcat认为请求path和war包名称相等匹配成功
if (uri.getLength() == length) {
found = true;
break;
} else if (uri.startsWithIgnoreCase("/", length)) {
//认为请求path是war包名称后面根/的匹配成功
found = true;
break;
}
}
}
Servlet查找
根据请求的path找到Host以及Host下对应的context后,开始匹配本次请求对应的Servlet,通过internalMapWrapper方法实现,tomcat叫做匹配Wrapper,核心代码如下
//tomcat 传过来的都是一个字符数组,path的每一部分都是通过
//offset和长度来代表的,
int pathOffset = path.getOffset();
int pathEnd = path.getEnd();
boolean noServletPath = false;
int length = contextVersion.path.length();
//noServletPath为true,就是请求路径只有context
if (length == (pathEnd - pathOffset)) {
noServletPath = true;
}
int servletPath = pathOffset + length;
path.setOffset(servletPath);
//开始匹配servlet
// Rule 1 -- Exact Match,,1是完全匹配,即没有通配符的servlet的
MappedWrapper[] exactWrappers = contextVersion.exactWrappers;
internalMapExactWrapper(exactWrappers, path, mappingData);
// Rule 2 -- Prefix Match,没有找到,按前缀匹配即/xxx/*这类servlet
boolean checkJspWelcomeFiles = false;
MappedWrapper[] wildcardWrappers = contextVersion.wildcardWrappers;
if (mappingData.wrapper == null) {
internalMapWildcardWrapper(wildcardWrappers, contextVersion.nesting,
path, mappingData);
if (mappingData.wrapper != null && mappingData.jspWildCard) {
char[] buf = path.getBuffer();
if (buf[pathEnd - 1] == '/') {
/*
* Path ending in '/' was mapped to JSP servlet based on
* wildcard match (e.g., as specified in url-pattern of a
* jsp-property-group.
* Force the context's welcome files, which are interpreted
* as JSP files (since they match the url-pattern), to be
* considered. See Bugzilla 27664.
*/
mappingData.wrapper = null;
checkJspWelcomeFiles = true;
} else {
// See Bugzilla 27704
mappingData.wrapperPath.setChars(buf, path.getStart(),
path.getLength());
mappingData.pathInfo.recycle();
}
}
}
网友评论