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

前端 未结 4 1589
礼貌的吻别
礼貌的吻别 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-27 09:29

    I will put a small comparison table here (just to have it somewhere):

    Servlet is mapped as /test%3F/* and the application is deployed under /app.

    http://30thh.loc:8480/app/test%3F/a%3F+b;jsessionid=S%3F+ID?p+1=c+d&p+2=e+f#a

    Method              URL-Decoded Result           
    ----------------------------------------------------
    getContextPath()        no      /app
    getLocalAddr()                  127.0.0.1
    getLocalName()                  30thh.loc
    getLocalPort()                  8480
    getMethod()                     GET
    getPathInfo()           yes     /a?+b
    getProtocol()                   HTTP/1.1
    getQueryString()        no      p+1=c+d&p+2=e+f
    getRequestedSessionId() no      S%3F+ID
    getRequestURI()         no      /app/test%3F/a%3F+b;jsessionid=S+ID
    getRequestURL()         no      http://30thh.loc:8480/app/test%3F/a%3F+b;jsessionid=S+ID
    getScheme()                     http
    getServerName()                 30thh.loc
    getServerPort()                 8480
    getServletPath()        yes     /test?
    getParameterNames()     yes     [p 2, p 1]
    getParameter("p 1")     yes     c d
    

    In the example above the server is running on the localhost:8480 and the name 30thh.loc was put into OS hosts file.

    Comments

    • "+" is handled as space only in the query string

    • Anchor "#a" is not transferred to the server. Only the browser can work with it.

    • If the url-pattern in the servlet mapping does not end with * (for example /test or *.jsp), getPathInfo() returns null.

    If Spring MVC is used

    • Method getPathInfo() returns null.

    • Method getServletPath() returns the part between the context path and the session ID. In the example above the value would be /test?/a?+b

    • Be careful with URL encoded parts of @RequestMapping and @RequestParam in Spring. It is buggy (current version 3.2.4) and is usually not working as expected.

提交回复
热议问题