URL、URI、ServletPath、ContextPath示例

獲取各種請求地址代碼:

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/*條件下進行

  1. 請求地址:http://localhost:8080/demo/hello/abcDispatcherServleturl-patternspring.mvc.servlet.path=/
contextPath: /demo
requestURI: /demo/hello/abc
servletPath: /hello/abc
pathInfo: null
requestURL: http://localhost:8080/demo/hello/abc
  1. 請求地址:http://localhost:8080/demo/hello/hello/abcDispatcherServleturl-patternspring.mvc.servlet.path=/hello
contextPath: /demo
requestURI: /demo/hello/hello/abc
servletPath: /hello
pathInfo: /hello/abc
requestURL: http://localhost:8080/demo/hello/hello/abc

結論:

servletPathpathInfo的結果與DispatcherServleturl-pattern配置有關,servletPath + pathInfo組成不含項目名的請求路徑(以下符號-爲減號

  1. url-pattern/
    servletPathrequestURI - 項目名
    pathInfonull
  2. url-pattern/other時(這裏的other表示其他任意路徑)
    servletPath/other
    pathInforequestURI - 項目名 - servletPath
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章