在servlet处理请求的路径时request里有几个常用的函数:
getRequestURL()
getRequestURI()
getContextPath()
getServletPath()
getPathInfo()
这里的前三个函数的返回值基本是可以预期的,与servlet映射的URL基本没关系,而后两个返回的值就是与servlet映射的URL相关的了。(对于URL和URI的关系,请看这里)
先看一下前三个:
访问 : 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.
关于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.
扩展阅读:
关于servlet mapping
网友评论