[英]What's the difference between getRequestURI and getPathInfo methods in HttpServletRequest?
我正在制作一個簡單,非常輕巧的前置控制器。 我需要將請求路徑與不同的處理程序(操作)匹配,以便選擇正確的路徑。
在我的本地機器上HttpServletRequest.getPathInfo()
和HttpServletRequest.getRequestURI()
返回相同的結果。 但我不確定它們會在生產環境中返回什么。
那么,這些方法和我應該選擇什么之間的區別是什么?
我會在這里放一個小的比較表(只是為了讓它在某處):
Servlet映射為/test%3F/*
,應用程序部署在/app
。
http://30thh.loc:8480/app/test%3F/a%3F+b;jsessionid=S%3F+ID?p+1=c+d&p+2=e+f#a
Method URL-Decoded Result
----------------------------------------------------
getContextPath() no /app
getLocalAddr() 127.0.0.1
getLocalName() 30thh.loc
getLocalPort() 8480
getMethod() GET
getPathInfo() yes /a?+b
getProtocol() HTTP/1.1
getQueryString() no p+1=c+d&p+2=e+f
getRequestedSessionId() no S%3F+ID
getRequestURI() no /app/test%3F/a%3F+b;jsessionid=S+ID
getRequestURL() no http://30thh.loc:8480/app/test%3F/a%3F+b;jsessionid=S+ID
getScheme() http
getServerName() 30thh.loc
getServerPort() 8480
getServletPath() yes /test?
getParameterNames() yes [p 2, p 1]
getParameter("p 1") yes c d
在上面的示例中,服務器在localhost:8480
上運行,名稱30thh.loc
被放入OS hosts
文件中。
評論
“+”僅在查詢字符串中作為空格處理
錨“#a”未傳輸到服務器。 只有瀏覽器可以使用它。
如果servlet映射中的url-pattern
不以*
結尾(例如/test
或*.jsp
),則getPathInfo()
將返回null
。
如果使用Spring MVC
方法getPathInfo()
返回null
。
方法getServletPath()
返回上下文路徑和會話ID之間的部分。 在上面的例子中,值是/test?/a?+b
在Spring中要小心@RequestMapping
和@RequestParam
URL編碼部分。 它是錯誤的(當前版本3.2.4)並且通常不按預期工作 。
getPathInfo()
在URI之后提供額外的路徑信息,用於訪問您的Servlet,其中getRequestURI()
提供完整的URI。
我認為它們會有所不同,因為Servlet必須首先配置自己的URI模式; 我不認為我曾經從根(/)服務過Servlet。
例如,如果Servlet'Foo'映射到URI'/ foo',那么我會想到URI:
/foo/path/to/resource
會導致:
RequestURI = /foo/path/to/resource
和
PathInfo = /path/to/resource
讓我們分解客戶端在其地址欄中鍵入的完整URL以訪問您的servlet:
http://www.example.com:80/awesome-application/path/to/servlet/path/info?a=1&b=2#boo
部分是:
http
www.example.com
80
awesome-application
path/to/servlet
path/info
a=1&b=2
boo
請求URI(由getRequestURI返回)對應於第4,5和6部分。
(順便說一句,即使你沒有要求這個,方法getRequestURL會給你第1,2,3,4,5和6部分)。
現在:
以下內容始終成立(URL編碼差異除外):
requestURI = contextPath + servletPath + pathInfo
Servlet 3.0規范中的以下示例非常有用:
注意:圖片如下,我沒有時間在HTML中重新創建:
考慮以下servlet conf:
<servlet>
<servlet-name>NewServlet</servlet-name>
<servlet-class>NewServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>NewServlet</servlet-name>
<url-pattern>/NewServlet/*</url-pattern>
</servlet-mapping>
現在,當我點擊URL http://localhost:8084/JSPTemp1/NewServlet/jhi
,它將調用NewServlet
因為它使用上述模式進行映射。
這里:
getRequestURI() = /JSPTemp1/NewServlet/jhi
getPathInfo() = /jhi
我們有那些:
getPathInfo()
回報
一個字符串,由Web容器解碼,指定在servlet路徑之后但在請求URL中的查詢字符串之前的額外路徑信息; 如果URL沒有任何額外的路徑信息,則返回null
getRequestURI()
回報
一個String,包含從協議名稱到查詢字符串的URL部分
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.