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:
StringBuffer url = req.getRequestURL();
String uri = req.getRequestURI();
String ctx = req.getContextPath();
String base = url.substring(0, url.length() - uri.length() + ctx.length()) + "/";
Your ctxUrl.substring(0, ctxUrl.lastIndexOf("/")));
approach will fail on URLs with multiple folders like http://server.name:8080/context/folder1/folder2/folder3
.
The following will get the context URL and resolve things appropriately.
URI contextUrl = URI.create(req.getRequestURL().toString()).resolve(req.getContextPath());
This will do all the necessary processing for ports, slashes and what not. It will also work for the root context as req.getContextPath() will return ""
If you are using a proxy server you need to ensure that the original Host:
request is passed in (e.g. Apache ProxyPass instructions to ProxyPreserveHost
.
Suppose,
We want to get http://server.name:8080/context/ from anywhere in Java web app project.
String uri = request.getRequestURI();
//uri = "/context/someAction"
String url = request.getRequestURL().toString();
// url = "http://server.name:8080/context/someAction"
String ctxPath = request.getContextPath();
// ctxPath = "/context";
url = url.replaceFirst(uri, "");
// url = "http://server.name:8080"
url = url + ctxPath;
//url = "http://server.name:8080/context"
using this code block, we can get the URL
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With