在servlet處理請求的路徑時request里有幾個常用的函數(shù):
getRequestURL()
getRequestURI()
getContextPath()
getServletPath()
getPathInfo()
這里的前三個函數(shù)的返回值基本是可以預期的,與servlet映射的URL基本沒關(guān)系,而后兩個返回的值就是與servlet映射的URL相關(guān)的了篙挽。(對于URL和URI的關(guān)系刁标,請看這里)
先看一下前三個:
訪問 : http://localhost:8080/myapp/test/first.html
URL : http://localhost:8080/myapp/test/first.html
URI : /myapp/test/first.html
ContextPath : /myapp
StringBuffer getRequestURL()
Reconstructs the URL the client used to make the request. The returned URL contains a protocol, server name, port number, and server path, but it does not include query string parameters.
String getRequestURI()
Returns the part of this request's URL from the protocol name up to the query string in the first line of the HTTP request. The web container does not decode this String. For example:
First line of HTTP request | Returned Value |
---|---|
POST /some/path.html HTTP/1.1 | /some/path.html |
GET http://foo.bar/a.html HTTP/1.0 | /a.html |
HEAD /xyz?a=b HTTP/1.1 | /xyz |
String getContextPath()
Returns the portion of the request URI that indicates the context of the request. The context path always comes first in a request URI. The path starts with a "/" character but does not end with a "/" character. For servlets in the default (root) context, this method returns "". The container does not decode this string.
關(guān)于PathInfo和ServletPath
情況1(path mapping):
@WebServlet("/test1/*")
Request : http://localhost:8080/myapp/test1/first.html
ServletPath : /test1
PathInfo : /first.html
情況2(exact match):
@WebServlet("/test2/t2")
Request : http://localhost:8080/myapp/test2/t2
ServletPath : /test2/t2
PathInfo : null
情況3(extension mapping):
@WebServlet("*.do")
Request : http://localhost:8080/myapp/test3/t3.do
ServletPath : /test3/t3.do
PathInfo : null
情況4(default match):
@WebServlet("/")
Request : http://localhost:8080/myapp/
ServletPath : /
PathInfo : null
String getPathInfo()
Returns any extra path information associated with the URL the client sent when it made this request. The extra path information follows the servlet path but precedes the query string and will start with a "/" character.
This method returns null if there was no extra path information.
String getServletPath()
Returns the part of this request's URL that calls the servlet. This path starts with a "/" character and includes either the servlet name or a path to the servlet, but does not include any extra path information or a query string. Same as the value of the CGI variable SCRIPT_NAME.
This method will return an empty string ("") if the servlet used to process this request was matched using the "/*" pattern.
擴展閱讀:
關(guān)于servlet mapping