在我的本地机器上,
HttpServletRequest.getPathInfo()
和HttpServletRequest.getRequestURI()
返回相同的结果。但我不确定它们在生产环境中会返回什么。那么,这些方法有什么区别,我应该选择哪个?
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
被放置在操作系统的 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),通常不能按预期工作。
getRequestURI()
和getRequestURL()
都应该返回未解码的jsessionid,即在这种情况下是S%3F+ID
。至少在Tomcat/8.5.6上是这样的。 - Gediminas RimsagetPathInfo()
返回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
getRequestURI()
像预期的那样给出字符串"/foo/path/to/resource"
,但是对于相同的HttpServletRequest
对象,getPathInfo()
却返回null
。这到底是怎么回事? 编辑:由用户“30thh”在下面回答了该问题。 - Snackoverflow让我们分解一下客户端在地址栏中输入以访问你的servlet的完整URL:
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规范的示例非常有帮助:
考虑以下servlet配置:
<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 容器解码,指定请求 URL 中在 Servlet 路径之后但在查询字符串之前的额外路径信息;如果 URL 没有任何额外路径信息,则返回 null。
getRequestURI()
返回
包含从协议名称到查询字符串的 URL 部分的字符串。