What's the difference between getRequestURI and getPathInfo methods in HttpServletRequest?

前端 未结 4 1579
礼貌的吻别
礼貌的吻别 2020-11-27 09:13

I\'m making a simple, very lightweight front-controller. I need to match request paths to different handlers (actions) in order to choose the correct one.

On my loca

4条回答
  •  时光取名叫无心
    2020-11-27 09:39

    Let's break down the full URL that a client would type into their address bar to reach your servlet:

    http://www.example.com:80/awesome-application/path/to/servlet/path/info?a=1&b=2#boo

    The parts are:

    1. scheme: http
    2. hostname: www.example.com
    3. port: 80
    4. context path: awesome-application
    5. servlet path: path/to/servlet
    6. path info: path/info
    7. query: a=1&b=2
    8. fragment: boo

    The request URI (returned by getRequestURI) corresponds to parts 4, 5 and 6.

    (incidentally, even though you're not asking for this, the method getRequestURL would give you parts 1, 2, 3, 4, 5 and 6).

    Now:

    • part 4 (the context path) is used to select your particular application out of many other applications that may be running in the server
    • part 5 (the servlet path) is used to select a particular servlet out of many other servlets that may be bundled in your application's WAR
    • part 6 (the path info) is interpreted by your servlet's logic (e.g. it may point to some resource controlled by your servlet).
    • part 7 (the query) is also made available to your servlet using getQueryString
    • part 8 (the fragment) is not even sent to the server and is relevant and known only to the client

    The following always holds (except for URL encoding differences):

    requestURI = contextPath + servletPath + pathInfo
    

    The following example from the Servlet 3.0 specification is very helpful:


    Note: image follows, I don't have the time to recreate in HTML:

提交回复
热议问题