Get Root/Base Url In Spring MVC

Solution 1:

I prefer to use

final String baseUrl = ServletUriComponentsBuilder.fromCurrentContextPath().build().toUriString();

It returns a completely built URL, scheme, server name and server port, rather than concatenating and replacing strings which is error prone.

Solution 2:

If base url is "http://www.example.com", then use the following to get the "www.example.com" part, without the "http://":

From a Controller:

@RequestMapping(value = "/someURL", method = RequestMethod.GET)
public ModelAndView doSomething(HttpServletRequest request) throws IOException{
    //Try this:
    request.getLocalName(); 
    // or this
    request.getLocalAddr();
}

From JSP:

Declare this on top of your document:

<c:set var="baseURL" value="${pageContext.request.localName}"/> //or ".localAddr"

Then, to use it, reference the variable:

<a href="http://${baseURL}">Go Home</a>

Solution 3:

You can also create your own method to get it:

public String getURLBase(HttpServletRequest request) throws MalformedURLException {

    URL requestURL = new URL(request.getRequestURL().toString());
    String port = requestURL.getPort() == -1 ? "" : ":" + requestURL.getPort();
    return requestURL.getProtocol() + "://" + requestURL.getHost() + port;

}

Solution 4:

Explanation

I know this question is quite old but it's the only one I found about this topic, so I'd like to share my approach for future visitors.

If you want to get the base URL from a WebRequest you can do the following:

ServletUriComponentsBuilder.fromRequestUri(HttpServletRequest request);

This will give you the scheme ("http" or "https"), host ("example.com"), port ("8080") and the path ("/some/path"), while fromRequest(request) would give you the query parameters as well. But as we want to get the base URL only (scheme, host, port) we don't need the query params.

Now you can just delete the path with the following line:

ServletUriComponentsBuilder.fromRequestUri(HttpServletRequest request).replacePath(null);

TLDR

Finally our one-liner to get the base URL would look like this:

//request URL: "http://example.com:8080/some/path?someParam=42"

String baseUrl = ServletUriComponentsBuilder.fromRequestUri(HttpServletRequest request)
        .replacePath(null)
        .build()
        .toUriString();

//baseUrl: "http://example.com:8080"

Addition

If you want to use this outside a controller or somewhere, where you don't have the HttpServletRequest present, you can just replace

ServletUriComponentsBuilder.fromRequestUri(HttpServletRequest request).replacePath(null)

with

ServletUriComponentsBuilder.fromCurrentContextPath()

This will obtain the HttpServletRequest through spring's RequestContextHolder. You also won't need the replacePath(null) as it's already only the scheme, host and port.

Solution 5:

request.getRequestURL().toString().replace(request.getRequestURI(), request.getContextPath())