獲取各種請求地址代碼:
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