?
1、新建 Filter 类
@WebFilter("/*")
public class AccessFilter implements Filter
?
2、在doFilter方法中打印测试信息:
String pathInfo = ((HttpServletRequest)servletRequest).getPathInfo();
System.out.println("filter pathInfo: " + pathInfo);
?
3、新建Servlet类
@WebServlet(
urlPatterns = {?
"/api/*"
})
public class Dispatch extends HttpServlet?
?
4、在service方法中打印测试信息:
String pathInfo = request.getPathInfo();
System.out.println("servlet pathInfo: " + pathInfo);
?
5、启动Tomcat应用(应用上下文根 testLab)
?
6、访问URL:
http://localhost:8080/testWeb/api/aa/bb?a=a&b=b
打印结果:
filter pathInfo: /aa/bb
servlet pathInfo: /aa/bb
?
7、修改Dispatch Servlet的 urlPatterns 为 /*,重启Tomcat应用,再次访问:
http://localhost:8080/testWeb/api/aa/bb?a=a&b=b
打印结果:
filter pathInfo: /api/aa/bb
servlet pathInfo: /api/aa/bb
?
8、注释掉 Dispatch Servlet,重启应用,再次访问:
http://localhost:8080/testWeb/api/aa/bb?a=a&b=b
打印结果:
filter pathInfo: null
?
官方文档中关于getPathInfo()的说明:
java.lang.String getPathInfo()Returns any extra path information associated with the URL the client sent when it made this request. The extra path information follows the servlet path but precedes the query string and will start with a "/" character.?
This method returns null if there was no extra path information.
?
理解:
1、getPathInfo()只与匹配到的servlet有关,其值是请求URL的servlet-mapping之后,query-string之前的部分,并且以 "/" 打头。
2、如果getPathInfo()找不到匹配的servlet,则其值始终是null。
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?