HttpServletRequest中的getRequestURI和getPathInfo方法有什么区别?

2022-08-31 07:08:32

我正在制作一个简单,非常轻巧的前置控制器。我需要将请求路径与不同的处理程序(操作)相匹配,以便选择正确的处理程序(操作)。

在我的本地机器上,HttpServletRequest.getPathInfo()HttpServletRequest.getRequestURI() 返回相同的结果。但我不确定它们在生产环境中会返回什么。

那么,这些方法有什么区别,我应该选择什么?


答案 1

我将在这里放一个小的比较表(只是为了把它放在某个地方):

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

在上面的示例中,服务器正在 上运行,并且名称已放入 OS 文件中。localhost:848030thh.lochosts

评论

  • “+”仅在查询字符串中作为空格处理

  • 锚点“#a”不会传输到服务器。只有浏览器可以使用它。

  • 如果 servlet 映射中的 不以 结尾(例如 或 ),则返回 。url-pattern*/test*.jspgetPathInfo()null

如果使用弹簧MVC

  • 方法返回 。getPathInfo()null

  • 方法返回上下文路径和会话 ID 之间的部分。在上面的示例中,该值为getServletPath()/test?/a?+b

  • 小心 URL 编码的部分 和 在春天。它是错误的(当前版本3.2.4),通常无法按预期工作@RequestMapping@RequestParam


答案 2

getPathInfo()在 URI 之后提供额外的路径信息,用于访问您的 Servlet,其中 as 给出了完整的 URI。getRequestURI()

我本来以为它们会有所不同,因为Servlet首先必须配置自己的URI模式;我不认为我曾经从根(/)提供过Servlet。

例如,如果Servlet 'Foo'映射到URI '/foo',那么我会认为URI:

/foo/path/to/resource

将导致:

RequestURI = /foo/path/to/resource

PathInfo = /path/to/resource

推荐