---
title: "tomcat 如何把请求(request)映射到servlet "
author: "robertliudeqiang"
date: "2010-01-22T12:53:11Z"
tags: []
categories: ["Web前端"]
slug: "tomcat-request-servlet"
draft: false
lastmod: "2010-01-22T15:57:42Z"
id: 577312
url: "https://robblog.iteye.com/blog/577312"
---

先搞清servlet的几个概念:
**RequestURI(请求URI)**
表示客户端(浏览器)请求的URL，例如一个链接http://localhost/app/test，那么request URL就是/app/test。RequestURI不浩瀚查询参数。
RequestURI可以使用request.getRequestURI()获取。

**context path(上下文路径)**
表示了一个应用(web application)，例如一个链接http://localhost/app/test，那么context pathL就是/app。
context path可以使用request.getContextPath()获取。

**ServletPath**
用来找servlet的部分。例如一个链接http://localhost/app/test，那么用来进行servlet mapping的字符串就是/test，注意这个URI中是没有path info的。

**tomcat的匹配规则:**
tomcat是根据web.xml中的<url-pattern>标签来匹配的，匹配规则如下:

1 Exact Match(完全匹配)

2 Prefix Match(前缀匹配) 
匹配字符串以"/*"结尾，是最长路径匹配
例如http://localhost/app/test/a，在匹配/test/*和/test/a/*时，会匹配后者

3 Extension Match(扩展匹配)
匹配字符串以"*."开头。

4 Welcome资源处理
  4a Welcome resources processing for exact macth
  4b Welcome resources processing for prefix match
  4c Welcome resources processing for physical folder

5 Default servlet
定义在global的$CATALINA_HOME/conf/web.xml中，下面是缺省定义
    <servlet>
        <servlet-name>default</servlet-name>
        <servlet-class>
          org.apache.catalina.servlets.DefaultServlet
        </servlet-class>
        <init-param>
            <param-name>debug</param-name>
            <param-value>0</param-value>
        </init-param>
        <init-param>
            <param-name>listings</param-name>
            <param-value>true</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
...
    <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
可以修改这个配置。

匹配规则可以参考servlet 3.0文档和tomcat源码。

**tomcat的源码:**
org.apache.tomcat.util.http.mapper.Mapper类
主要匹配方法 internalMapWrapper()