Get absolute URL of site Grails application is available at?

14 / Oct / 2010 by Deepak Mittal 7 comments

Many times, we need to get the absolute URL of the site/application. One such case is when we are sending out links to the application in emails.

The default Config.groovy file provided by Grails has a property with the name grails.serverURL. I have typically used it to get absolute URL (environment specific)  of the site Grails application is available at.

This approach breaks in case the application is available as different sites i.e. the same application is  used to render multiple sites.  Here we need to get the absolute URL of the site that is serving the request (instead of application wide URL).

We could use inject a utility method to HttpServletRequest class (similar to isXhr method injected by Grails in the same class)

[groovy]
javax.servlet.http.HttpServletRequest.metaClass.getSiteUrl = {
return (delegate.scheme + "://" + delegate.serverName + ":" + delegate.serverPort + delegate.getContextPath())
}
[/groovy]

After we do this, we could simply say request.siteUrl to get the absolute URL of the site serving the request. You might want to get rid of serverPort in the above method if the server is running on standard HTTP ports (80/443).

Hope you find it handy!

-Deepak

FOUND THIS USEFUL? SHARE IT

comments (7)

  1. Apu

    When I am using
    delegate.scheme + “://” + delegate.serverName + “:” + delegate.serverPort + delegate.getContextPath()

    we have apache which is reroute the request to tomcat
    will give url with war file name
    for e.g
    https://websitename:443/warFileName/….

    how can i get rid of warFileName

    Reply
  2. Bhagwat Kumar

    Hi Josh,
    You can use Bootstrap.groovy for this purpose instead of injecting the dynamic method each time a filter is called.

    Reply
  3. Josh Diehl

    Needed this for a project, I ended up creating a Filter to do it for all controllers:

    class SiteChooserFilters {

    def filters = {
    all(controller:’*’, action:’*’) {
    before = {
    javax.servlet.http.HttpServletRequest.metaClass.getSiteUrl = {
    return (delegate.scheme + “://” + delegate.serverName + “:” + delegate.serverPort + delegate.getContextPath())
    }
    }
    }
    }
    }

    Reply

Leave a Reply to LogonTM Cancel reply

Your email address will not be published. Required fields are marked *