如何获取没有上下文path的请求URI?
方法request.getRequestURI()返回带有上下文path的URI。
例如,如果应用程序的基本URL是http://localhost:8080/myapp/ (即上下文path是myapp ),并且我为http://localhost:8080/myapp/secure/users调用request.getRequestURI() http://localhost:8080/myapp/secure/users ,它将返回/myapp/secure/users 。 
 有什么办法我们可以只得到这部分/secure/users ,即没有上下文path的URI? 
 如果你在一个映射到前缀模式的前端控制器servlet中,那么你可以使用HttpServletRequest#getPathInfo() 。 
 String pathInfo = request.getPathInfo(); // ... 
 假设你的示例中的servlet被映射到/secure ,那么这将返回/users ,这将是典型的前端控制器servlet中唯一感兴趣的信息。 
 但是,如果servlet映射到后缀模式(但是,您的URL示例并不表示这是事实),或者当您真的在filter内部时(即将调用的servlet不一定已确定,那么getPathInfo()可以返回null ),那么你最好的办法就是使用通常的String方法根据上下文path的长度自己对请求URI进行子String处理: 
 HttpServletRequest request = (HttpServletRequest) req; String path = request.getRequestURI().substring(request.getContextPath().length()); // ... 
 request.getRequestURI().substring(request.getContextPath().length()) 
spring你可以做:
 String path = new UrlPathHelper().getPathWithinApplication(request); 
getPathInfo()有时返回null。 在文档HttpServletRequest
如果没有额外的path信息,此方法返回null。
我需要获取path文件没有在上下文path和getPathInfo()返回我空。 所以我使用另一种方法:httpRequest.getServletPath()
 public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; String newPath = parsePathToFile(httpRequest.getServletPath()); ... } 
如果你在Filter中使用request.getPathInfo(),你总是会得到null(至less在jetty中)。
这个简洁无效的bug +响应暗示了我认为的问题:
https://issues.apache.org/bugzilla/show_bug.cgi?id=28323
我怀疑这与servlet获取请求之前运行的filter有关。 这可能是一个容器错误,或者我无法识别的预期行为。
contextPath可用,所以即使在filter中,fforws解决scheme也可以工作。 我不喜欢必须手工完成,但执行被破坏或
做到这一点的一种方法是从请求URI中restservelet上下文path。
 String p = request.getRequestURI(); String cp = getServletContext().getContextPath(); if (p.startsWith(cp)) { String.err.println(p.substring(cp.length()); } 
在这里阅读。
也许你可以使用split方法来消除“/ myapp”,例如:
 string[] uris=request.getRequestURI().split("/"); string uri="/"+uri[1]+"/"+uris[2];