Question

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?

Was it helpful?

Solution

The answer is request.forwardURI (details here).

OTHER TIPS

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("/", 8))

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

    if(request.getAttribute("javax.servlet.forward.query_string")){

        sb << "?"

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

    return sb.toString();
}

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

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

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

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 org.springframework.security.web.PortResolverImpl()).getServerPort(request)
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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top