Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getting URL to a webapp context (the base URL)

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?

like image 230
Oleg Mikheev Avatar asked Jan 10 '13 02:01

Oleg Mikheev


3 Answers

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.

See also:

  • How to use relative paths without including the context root name? (for a JSP answer)
  • How get the base URL? (for a JSF answer)
like image 179
BalusC Avatar answered Nov 17 '22 13:11

BalusC


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.

like image 17
Archimedes Trajano Avatar answered Nov 17 '22 13:11

Archimedes Trajano


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

like image 2
mhmuftee Avatar answered Nov 17 '22 13:11

mhmuftee