Get Root/Base Url In Spring MVC

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.


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;

}

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>