Mike Flynn
Mike Flynn

Reputation: 24325

Get Root/Base Url In Spring MVC

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

Upvotes: 60

Views: 153658

Answers (15)

tutiplain
tutiplain

Reputation: 1480

The following worked for me:

In the controller method, add a parameter of type HttpServletRequest. You can have this parameter and still have an @RequestBody parameter, which is what all the previous answers fail to mention.

@PostMapping ("/your_endpoint")
public ResponseEntity<Object> register(
   HttpServletRequest servletRequest,
   @RequestBody RegisterRequest request
) {

    String url = servletRequest.getRequestURL().toString();
    String contextPath = servletRequest.getRequestURI();
    String baseURL = url.replace(contextPath,"");

    /// .... Other code 

}

I tested this on Spring Boot 3.0.6.

Upvotes: 0

youhans
youhans

Reputation: 6849

I had the exact requirement and reached to below solution:

String baseUrl = ServletUriComponentsBuilder.fromCurrentContextPath()
                    .replacePath(null).replaceQuery(null).fragment(null).build().toUriString();

For this code to work, it should run inside a thread bound to a Servlet request.

Upvotes: 0

Karl.S
Karl.S

Reputation: 2402

Simply :

/*
 * Returns the base URL from a request.
 *
 * @example: http://myhost:80/myapp
 * @example: https://mysecuredhost:443/
 */
String getBaseUrl(HttpServletRequest req) {
  return ""
    + req.getScheme() + "://"
    + req.getServerName()
    + ":" + req.getServerPort()
    + req.getContextPath();
}

Upvotes: 12

Ba_Ro_Na
Ba_Ro_Na

Reputation: 1

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```

Upvotes: 0

Arvind Kumar
Arvind Kumar

Reputation: 609

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

Upvotes: 0

Mirko Brandt
Mirko Brandt

Reputation: 475

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.

Upvotes: 20

Enoobong
Enoobong

Reputation: 1734

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.

Upvotes: 77

Fangxing
Fangxing

Reputation: 6115

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

Upvotes: 2

Hoa Nguyen
Hoa Nguyen

Reputation: 14540

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;

}

Upvotes: 18

Alexander Torstling
Alexander Torstling

Reputation: 18898

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:[email protected]/root/some?k=v#hey)
URI requestUri = new URI(req.getRequestURL().toString());
// and strip last parts (http://user:[email protected]/root)
URI contextUri = new URI(requestUri.getScheme(), 
                         requestUri.getAuthority(), 
                         req.getContextPath(), 
                         null, 
                         null);

You can then use UriComponentsBuilder from that URI:

// http://user:[email protected]/root/some/other/14
URI complete = UriComponentsBuilder.fromUri(contextUri)
                                   .path("/some/other/{id}")
                                   .buildAndExpand(14)
                                   .toUri();

Upvotes: 8

Wins
Wins

Reputation: 3460

In controller, use HttpServletRequest.getContextPath().

In JSP use Spring's tag library: or jstl

Upvotes: 9

Salim Hamidi
Salim Hamidi

Reputation: 21381

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

Upvotes: 11

Nahn
Nahn

Reputation: 3256

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>

Upvotes: 29

jakobklamra
jakobklamra

Reputation: 49

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.

Upvotes: 0

danny.lesnik
danny.lesnik

Reputation: 18639

     @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

Upvotes: 1

Related Questions