Sometimes you need to construct a full URL to your web app context inside a servlet/JSP/whatever based on HttpServletRequest.
Something like http://server.name:8080/context/. Servlet API doesn’t have a single method to achieve this.
The straightforward approach is to append all URL components to a StringBuffer, like
ctxUrl = sb.append(req.getScheme()).append("://")
.append(req.getgetServerName()).append(":")
.append(req.getServerPort()) etc
I wonder if there’s anything wrong with this alternative (which is 10 times faster):
ctxUrl = req.getRequestURL();
ctxUrl = ctxUrl.substring(0, ctxUrl.lastIndexOf("/")));
Will two above methods always produce the same result?
It’s called the "base URL" (the one you could use in HTML
<base>tag). You can obtain it as follows:Your
ctxUrl.substring(0, ctxUrl.lastIndexOf("/")));approach will fail on URLs with multiple folders likehttp://server.name:8080/context/folder1/folder2/folder3.See also: