获取各种请求地址代码:
String contextPath = request.getContextPath();
String servletPath = request.getServletPath();
String pathInfo = request.getPathInfo();
String requestURI = request.getRequestURI();
String requestURL = request.getRequestURL().toString();
结果示例:
以下测试均在contextPath
(项目名)为demo
,请求路径@GetMapping
为/hello/*
条件下进行
- 请求地址:http://localhost:8080/demo/hello/abc ,
DispatcherServlet
的url-pattern
:spring.mvc.servlet.path=/
contextPath: /demo
requestURI: /demo/hello/abc
servletPath: /hello/abc
pathInfo: null
requestURL: http://localhost:8080/demo/hello/abc
- 请求地址:http://localhost:8080/demo/hello/hello/abc ,
DispatcherServlet
的url-pattern
:spring.mvc.servlet.path=/hello
contextPath: /demo
requestURI: /demo/hello/hello/abc
servletPath: /hello
pathInfo: /hello/abc
requestURL: http://localhost:8080/demo/hello/hello/abc
结论:
servletPath
和pathInfo
的结果与DispatcherServlet
的url-pattern
配置有关,servletPath
+ pathInfo
组成不含项目名的请求路径(以下符号-
为减号)
url-pattern
为/
时
servletPath
为requestURI
- 项目名
pathInfo
为null
url-pattern
为/other
时(这里的other表示其他任意路径)
servletPath
为/other
pathInfo
为requestURI
- 项目名 -servletPath