How to get only part of URL from HttpServletRequest?

前端 未结 5 1954
花落未央
花落未央 2020-12-31 02:05

From the following URL I need to get (http://localhost:9090/dts) alone.
That is I need to remove (documents/savedoc) (OR)
need to get on

5条回答
  •  醉酒成梦
    2020-12-31 02:31

    Just remove URI from URL and then append context path to it. No need to fiddle with loose schemes and ports which is only more tedious when you're dealing with default port 80 which don't need to appear in URL at all.

    StringBuffer url = request.getRequestURL();
    String uri = request.getRequestURI();
    String ctx = request.getContextPath();
    String base = url.substring(0, url.length() - uri.length() + ctx.length());
    // ...
    

    See also:

    • Browser can't access/find relative resources like CSS, images and links when calling a Servlet which forwards to a JSP (for the JSP/JSTL variant of composing the base URL)

提交回复
热议问题