我正在制作一个简单,非常轻巧的前置控制器.我需要将请求路径与不同的处理程序(操作)匹配,以便选择正确的路径.
在我的本地计算机上HttpServletRequest.getPathInfo()并HttpServletRequest.getRequestURI()返回相同的结果.但我不确定它们会在生产环境中返回什么.
那么,这些方法和我应该选择什么之间的区别是什么?
30t*_*thh 428
我会在这里放一个小的比较表(只是为了让它在某处):
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
Run Code Online (Sandbox Code Playgroud)
在上面的示例中,服务器正在运行,localhost:8480并且名称30thh.loc已放入OS hosts文件中.
评论
"+"仅在查询字符串中作为空格处理
锚"#a"未传输到服务器.只有浏览器可以使用它.
如果url-patternservlet映射中没有以*(例如/test或*.jsp)结束,则getPathInfo()返回null.
如果使用Spring MVC
方法getPathInfo()返回null.
方法getServletPath()返回上下文路径和会话ID之间的部分.在上面的例子中,值将是/test?/a?+b
小心的URL编码的部分@RequestMapping和@RequestParam在春季.它是错误的(当前版本3.2.4)并且通常不按预期工作.
tro*_*foe 73
getPathInfo()在URI之后提供额外的路径信息,用于访问您的Servlet,其中getRequestURI()提供完整的URI.
我认为它们会有所不同,因为Servlet必须首先配置自己的URI模式; 我不认为我曾经从根(/)服务过Servlet.
例如,如果Servlet'Foo'映射到URI'/ foo',那么我会想到URI:
/foo/path/to/resource
Run Code Online (Sandbox Code Playgroud)
会导致:
RequestURI = /foo/path/to/resource
Run Code Online (Sandbox Code Playgroud)
和
PathInfo = /path/to/resource
Run Code Online (Sandbox Code Playgroud)
Mar*_*tus 25
让我们分解客户端在其地址栏中输入的完整URL以访问您的servlet:
http://www.example.com:80/awesome-application/path/to/servlet/path/info?a=1&b=2#boo
部分是:
httpwww.example.com80awesome-applicationpath/to/servletpath/infoa=1&b=2boo请求URI(由getRequestURI返回)对应于第4,5和6部分.
(顺便说一下,即使你没有要求这个,方法getRequestURL会给你第1,2,3,4,5和6部分).
现在:
以下内容始终成立(URL编码差异除外):
requestURI = contextPath + servletPath + pathInfo
Run Code Online (Sandbox Code Playgroud)
Servlet 3.0规范中的以下示例非常有用:
注意:图片如下,我没有时间在HTML中重新创建:
Jig*_*shi 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>
Run Code Online (Sandbox Code Playgroud)
现在,当我点击URL时http://localhost:8084/JSPTemp1/NewServlet/jhi,它将NewServlet在使用上述模式映射时调用.
这里:
getRequestURI() = /JSPTemp1/NewServlet/jhi
getPathInfo() = /jhi
Run Code Online (Sandbox Code Playgroud)
我们有那些:
getPathInfo()
返回
一个由Web容器解码的String,指定在servlet路径之后但在请求URL中的查询字符串之前的额外路径信息; 如果URL没有任何额外的路径信息,则返回null
getRequestURI()
返回
一个String,其中包含从协议名称到查询字符串的URL部分