问题
我正在制作一个简单,非常轻巧的前置控制器。我需要将请求路径与不同的处理程序(操作)匹配,以便选择正确的处理程序。
在我的本地机器HttpServletRequest.getPathInfo()
和HttpServletRequest.getRequestURI()
上返回相同的结果。但我不确定它们会在生产环境中返回什么。
那么,这些方法和我应该选择什么之间的区别是什么?
#1 热门回答(367 赞)
我会在这里放一个小的比较表(只是为了让它在某处):
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
已放入OShosts
文件中。
注释-""仅在查询字符串中作为空格处理
- 锚"#a"未传输到服务器。只有浏览器可以使用它。
- 如果servlet映射中的url-pattern不以结尾(例如/ test或 .jsp),则getPathInfo()返回null。
如果使用Spring MVC-方法getPathInfo()返回null。 - 方法getServletPath()返回上下文路径和会话ID之间的部分。在上面的例子中,值是/ test?/ a? b
- 在Spring中小心使用@RequestMapping和@RequestParam的URL编码部分。它是错误的(当前版本3.2.4)并且通常不能按预期工作。
#2 热门回答(62 赞)
getPathInfo()
在URI之后提供额外的路径信息,用于访问你的Servlet,其中asgetRequestURI()
提供完整的URI。
我认为它们会有所不同,因为Servlet必须首先配置自己的URI模式;我不认为我曾经从root(/)服务过Servlet。
例如,如果Servlet'Foo'映射到URI'/ foo',那么我会想到URI:
/foo/path/to/resource
会导致:
RequestURI = /foo/path/to/resource
和
PathInfo = /path/to/resource
#3 热门回答(16 赞)
考虑以下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>
现在,当我点击URLhttp://localhost:8084/JSPTemp1/NewServlet/jhi
时,它将调用NewServlet
,它将使用上述模式进行映射。
这里:
getRequestURI() = /JSPTemp1/NewServlet/jhi
getPathInfo() = /jhi
我们有那些:
- getPathInfo()返回一个由Web容器解码的String,指定在servlet路径之后但在请求URL中的查询字符串之前的额外路径信息;如果URL没有任何额外的路径信息,则返回null
- getRequestURI()返回一个String,其中包含从协议名称到查询字符串的URL部分