[jsp] How to get domain URL and application name?

Here's the scenario.

My Java web application has following path

https://www.mywebsite.com:9443/MyWebApp

Let's say there is a JSP file

https://www.mywebsite.com:9443/MyWebApp/protected/index.jsp

and I need to retrieve

https://www.mywebsite.com:9443/MyWebApp 

within this JSP file.

Of course, there is rather a lazy and silly way of just getting the URL and then re-tracing the path back.

But is there a programatic way of doing this? Specifically, I think I can get the domain + port, but how do I actually retrieve the application name "MyWebApp"?

This question is related to jsp base-url

The answer is


The following code might be useful for web application using JavaScript.

var newURL = window.location.protocol + "//"  + window.location.host + "" + window.location.pathname;

newURL = newURL.substring(0,newURL.indexOf(""));

The application name come from getContextPath.

I find this graphic from Agile Software Craftsmanship HttpServletRequest Path Decoding sorts out all the different methods that are available:

enter image description here


Take a look at the documentation for HttpServletRequest.
In order to build the URL in your example you will need to use:

  • getScheme()
  • getServerName()
  • getServerPort()
  • getContextPath()

Here is a method that will return your example:

public static String getURLWithContextPath(HttpServletRequest request) {
   return request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
}

If you are being passed a url as a String and want to extract the context root of that application, you can use this regex to extract it. It will work for full urls or relative urls that begin with the context root.

url.replaceAll("^(.*\\/\\/)?.*?\\/(.+?)\\/.*|\\/(.+)$", "$2$3")

I would strongly suggest you to read through the docs, for similar methods. If you are interested in context path, have a look here, ServletContext.getContextPath().