Get Root/Base Url In Spring MVC

早过忘川 提交于 2019-11-27 13:56:56

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>

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;

}

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

Wins

In controller, use HttpServletRequest.getContextPath().

In JSP use Spring's tag library: or jstl

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.

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();

Simply :

String getBaseUrl(HttpServletRequest req) {
    return req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + req.getContextPath();
}
danny.lesnik
     @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

jakobklamra

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.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!