通常当我们编写一个 Servlet 或 Filter 时,会要获取用户的请求路径。下面是获取请求路径的方法。
假设我们创建了一个 webapp 部署在 /app 路径下,webapp 里面有一个 Servlet 对应的路径为 /servlet1/*,那么当我们请求 http://localhost/app/servlet1/index 时,可以这样得到请求路径:
javaString fullPath = request.getRequestURI(); String outerPath = fullPath.substring(request.getContextPath().length()); String innerPath = outerPath.substring(request.getServletPath().length());
你就会得到
javafullPath = "/app/servlet1/index" outerPath = "/servlet1/index" innerPath = "/index"
注意,fullPath 当中不会包含 URL 参数,也就是说你请求 http://localhost/app/servlet1/index?name=a 时,得到的结果是一样的。
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用。你还可以使用@来通知其他用户。