Loading...

Thursday, January 12, 2012

Grails Goodness: Generate Links Outside Controllers or Tag Libraries

In Grails we can create a link to a controller with the link() method. This works in the context of a request, like in a controller, tag library or Groovy Server Page (GSP). But since Grails 2.0 we can also generate links in services or any other Spring bean in our project. To create a link we need to inject the grailsLinkGenerator bean into our class. The grailsLinkGenerator bean has a link() method with the same argument list as we are already used to. We can define for example the controller, action and other parameters and the method will return a correct link.

We can also create the link for a resource with the resource() method. And to get the context path and server base URL we use the methods getContextPath() and getServerBaseURL().

The following service uses the link generator to create links in a Grails service.

// File: grails-app/service/link/generator/LinkService.groovy
package link.generator

import org.codehaus.groovy.grails.web.mapping.LinkGenerator

class LinkService {

    // Inject link generator
    LinkGenerator grailsLinkGenerator

    String generate() {
        // Generate: http://localhost:8080/link-generator/sample/show/100
        grailsLinkGenerator.link(controller: 'sample', action: 'show', id: 100, absolute: true)
    }

    String resource() {
        // Generate: /link-generator/css/main.css
        grailsLinkGenerator.resource(dir: 'css', file: 'main.css')
    }

    String contextPath() {
        // Generate: /link-generator
        grailsLinkGenerator.contextPath
    }

    String serverUrl() {
        // Generate: http://localhost:8080/link-generator
        grailsLinkGenerator.serverBaseURL
    }
}

2 comments:

Anonymous said...

nice post...
but LinkGenerator is not available in grails 1.3.5..and i'm still using that version..
i want to ask is there a way to generate absolute link in grails job?
I'm using quartz plugin and need to generate absolute link to my controller and action url..
thank you..

Bart Wood said...

Thank you!!

Post a Comment