Getting the URL of the current page in Grails

Tag: grails Author: qq345606557 Date: 2009-08-24

In a Grails application I'd like to send a user from page A, then to a form on page B and then back to page A again.

To keep track of which URL to return to I send a "returnPage" parameter to page B containing the URL of page to return to (page A).

Currently I'm using request.getRequestURL() on page A to retrieve the page's URL. However, the URL I get from getRequestURL() does not correspond to the URL the end-user has in his/hers address bar:

request.getRequestURL() == "http://localhost:8080/something/WEB-INF/grails-app/views/layouts/main.gsp"
URL in address bar == "http://localhost:8080/something/some/thing"

How do I obtain the "end-user" URL?

Best Answer

The answer is request.forwardURI (details here).


Other Answer1

I built this method to get current url.

static String getCurrentUrl(HttpServletRequest request){

    StringBuilder sb = new StringBuilder()

    sb << request.getRequestURL().substring(0,request.getRequestURL().indexOf("/", 7))

    sb << request.getAttribute("javax.servlet.forward.request_uri")


        sb << "?"

        sb << request.getAttribute("javax.servlet.forward.query_string")

    return sb.toString();


works like a charm.

Other Answer2

My solution (Grails 1.3.7) is this one, you can copy and paste it into your controller:

boolean includePort = true;
String scheme = request.getScheme();
String serverName = request.getServerName();
int serverPort = (new
String contextPath = request.getContextPath();
boolean inHttp = "http".equals(scheme.toLowerCase());
boolean inHttps = "https".equals(scheme.toLowerCase());

if (inHttp && (serverPort == 80)) {
    includePort = false;
} else if (inHttps && (serverPort == 443)) {
    includePort = false;
String redirectUrl = scheme + "://" + serverName + ((includePort) ? (":" + serverPort) : "") + contextPath;

In our application, we cannot just use g.createLink(.. absolute:true) because we have different end-user URLs because of multiple customers.

Other Answer3

When creating the link to page B you can use the createLink tag to set the returnPage parameter:

<g:link controller="pageB" 
        params='[returnPage:createLink(action:actionName, params:params)]'>
  Go to Page B

Other Answer4

I prefer to use:

createLink(action: "index", controller:"user", absolute: true)
// http://localhost:8080/project/user

when I need to get an absolute url!

It's interesting to get relative path too:

createLink(action: "index", controller:"user")
// /project/user


the question says current page...