spring-mvcbase-url

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


Solution

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