tomcat 如何把請求(request)映射到servlet

先搞清servlet的幾個概念:
[b]RequestURI(請求URI)[/b]
表示客戶端(瀏覽器)請求的URL,例如一個鏈接http://localhost/app/test,那麼request URL就是/app/test。RequestURI不浩瀚查詢參數。
RequestURI可以使用request.getRequestURI()獲取。

[b]context path(上下文路徑)[/b]
表示了一個應用(web application),例如一個鏈接http://localhost/app/test,那麼context pathL就是/app。
context path可以使用request.getContextPath()獲取。

[b]ServletPath[/b]
用來找servlet的部分。例如一個鏈接http://localhost/app/test,那麼用來進行servlet mapping的字符串就是/test,注意這個URI中是沒有path info的。

[b]tomcat的匹配規則:[/b]
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源碼。

[b]tomcat的源碼:[/b]
org.apache.tomcat.util.http.mapper.Mapper類
主要匹配方法 internalMapWrapper()
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章