39

What is the best way to get the root/base url of a web application in Spring MVC?

Base Url = http://www.example.com or http://www.example.com/VirtualDirectory

Martijn Pieters
  • 889,049
  • 245
  • 3,507
  • 2,997
Mike Flynn
  • 21,905
  • 50
  • 167
  • 308

13 Answers13

46

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.

Enoobong
  • 1,204
  • 1
  • 14
  • 25
  • 3
    I was looking for this one because this can be used everywhere, even at app startup. – Csa77 Aug 09 '19 at 07:08
  • 1
    It's what I was looking for! – Nasta Feb 10 '20 at 00:35
  • It does not work: java.lang.IllegalStateException: No current ServletRequestAttributes I'm using it in @EventListener(ApplicationReadyEvent.class) handler, trying to use app base url for something, but it does not work. SpringBoot 2.1.7 – Tomasz Modelski Sep 23 '20 at 13:09
  • Same here, I get that error anywhere but in the controller. I think it needs a request context to work. – snakedog Apr 09 '21 at 23:49
28

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>
Nahn
  • 3,018
  • 21
  • 23
  • or, from the JSP you can set the value of the "baseURL" variable dirrectly with the **"http://"** prefix – Nahn Oct 24 '13 at 08:20
  • he method getLocalAddr() is undefined for the type HttpServletRequest – Sameer Kazi Aug 25 '16 at 10:11
  • 1
    Tbh you shouldn't use this as it's quite an old answer and is not up to date anymore. Have a look at my answer https://stackoverflow.com/questions/5012525/get-root-base-url-in-spring-mvc/57800880#57800880 – Mirko Brandt Sep 05 '19 at 08:01
18

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;

}
Hoa Nguyen
  • 10,964
  • 11
  • 42
  • 42
  • 1
    The problem with this is that the URL is taken from the request. Meaning, if a certificate is signed for *.example.com, which resolves to 192.168.42.1 and the request was made with the IP address instead of the name, it will cause issues. The best way is to configure (hard code) the name somewhere in the application's configuration. This way, when sending things like emails, your emails will be more legit and trusted. – TheRealChx101 Jun 22 '20 at 10:03
11

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

Salim Hamidi
  • 18,947
  • 1
  • 20
  • 28
11

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.

Mirko Brandt
  • 387
  • 2
  • 8
9

In controller, use HttpServletRequest.getContextPath().

In JSP use Spring's tag library: or jstl

Evgeni Dimitrov
  • 19,437
  • 29
  • 105
  • 137
Wins
  • 3,083
  • 3
  • 29
  • 61
9

Simply :

String getBaseUrl(HttpServletRequest req) {
    return req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + req.getContextPath();
}
Karl.S
  • 1,716
  • 1
  • 18
  • 31
7

Either inject a UriCompoenentsBuilder:

@RequestMapping(yaddie yadda)
public void doit(UriComponentBuilder b) {
  //b is pre-populated with context URI here
}

. Or make it yourself (similar to Salims answer):

// Get full URL (http://user:pwd@www.example.com/root/some?k=v#hey)
URI requestUri = new URI(req.getRequestURL().toString());
// and strip last parts (http://user:pwd@www.example.com/root)
URI contextUri = new URI(requestUri.getScheme(), 
                         requestUri.getAuthority(), 
                         req.getContextPath(), 
                         null, 
                         null);

You can then use UriComponentsBuilder from that URI:

// http://user:pwd@www.example.com/root/some/other/14
URI complete = UriComponentsBuilder.fromUri(contextUri)
                                   .path("/some/other/{id}")
                                   .buildAndExpand(14)
                                   .toUri();
Alexander Torstling
  • 16,682
  • 6
  • 55
  • 70
2

In JSP

<c:set var="scheme" value="${pageContext.request.scheme}"/>
<c:set var="serverPort" value="${pageContext.request.serverPort}"/>
<c:set var="port" value=":${serverPort}"/>

<a href="${scheme}://${pageContext.request.serverName}${port}">base url</a>

reference https://github.com/spring-projects/greenhouse/blob/master/src/main/webapp/WEB-INF/tags/urls/absoluteUrl.tag

fangxing
  • 3,706
  • 1
  • 32
  • 42
1
     @RequestMapping(value="/myMapping",method = RequestMethod.POST)
      public ModelandView myAction(HttpServletRequest request){

       //then follow this answer to get your Root url
     }

Root URl of the servlet

If you need it in jsp then get in in controller and add it as object in ModelAndView.

Alternatively, if you need it in client side use javascript to retrieve it: http://www.gotknowhow.com/articles/how-to-get-the-base-url-with-javascript

Community
  • 1
  • 1
danny.lesnik
  • 18,032
  • 28
  • 123
  • 194
  • Personally, I would use this answer to get it in a JSP: http://stackoverflow.com/questions/4278445/jsp-how-to-get-base-url-cleanly-without-javascript/4278830#4278830 – nickdos Feb 16 '11 at 23:02
0

If you just interested in the host part of the url in the browser then directly from request.getHeader("host")) -

import javax.servlet.http.HttpServletRequest;

@GetMapping("/host")
public String getHostName(HttpServletRequest request) {

     request.getLocalName() ; // it will return the hostname of the machine where server is running.

     request.getLocalName() ; // it will return the ip address of the machine where server is running.


    return request.getHeader("host"));

}

If the request url is https://localhost:8082/host

localhost:8082

Arvind Kumar
  • 301
  • 4
  • 13
0

Here:

In your .jsp file inside the [body tag]

<input type="hidden" id="baseurl" name="baseurl" value=" " />

In your .js file

var baseUrl = windowurl.split('://')[1].split('/')[0]; //as to split function 
var xhr = new XMLHttpRequest();
var url='http://'+baseUrl+'/your url in your controller';
xhr.open("POST", url); //using "POST" request coz that's what i was tryna do
xhr.send(); //object use to send```
  • 1
    Welcome to SO! Please read the [tour](https://stackoverflow.com/tour), and [How do I write a good answer?](https://stackoverflow.com/help/how-to-answer) – Tomer Shetah Dec 16 '20 at 12:54
0

I think the answer to this question: Finding your application's URL with only a ServletContext shows why you should use relative url's instead, unless you have a very specific reason for wanting the root url.

Community
  • 1
  • 1
jakobklamra
  • 49
  • 1
  • 1
  • 3