Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 847
Mike Flynn Avatar asked Feb 16 '11 04:02

Mike Flynn


3 Answers

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.

like image 113
Enoobong Avatar answered Nov 06 '22 23:11

Enoobong


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>
like image 38
Nahn Avatar answered Nov 06 '22 22:11

Nahn


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;

}
like image 18
Hoa Nguyen Avatar answered Nov 06 '22 22:11

Hoa Nguyen