http://www.jellyfishtechnologies.com/generate-link-grails-services/


We can easily generate links in grails controllers, gsps and tag libraries using g.link method of grails tag library. But tag libraries are not accessible in the grails services.

Grails provide us grailsLinkGenerator bean to create links in the grails services.

First inject the grailsLinkGenerator bean in the service

1def grailsLinkGenerator

then call link method of the the bean to create link

1log.info grailsLinkGenerator.link(controller: 'controllerName', action: 'actionName')
2log.info grailsLinkGenerator.link(controller: 'controllerName', action: 'actionName', absolute: true)
3log.info grailsLinkGenerator.link(controller: 'controllerName', action: 'actionName', id: 1, absolute: true)

output

1/appName/controllerName/actionName
2
3http://localhost:8080/appName/controllerName/actionName
4
5
6http://localhost:8080/appName/controllerName/actionName/1

link method of the bean supports all the attributes of the g.link method. GrailsLinkGenerator has serverBaseURL method to get the base URL of the server.

1log.info grailsLinkGenerator.link(controller: 'controllerName', action: 'actionName', id: 1, base: grailsLinkGenerator.serverBaseURL)
2log.info grailsLinkGenerator.link(controller: 'controllerName', action: 'actionName', params: [id: 1, name: 'Manish Bharti'], absolute: true)

using grailsLinkGenerator we can also generate the web-app resources

1log.info grailsLinkGenerator.resource(dir: 'p_w_picpaths', file: 'apple-touch-icon.png')
2log.info grailsLinkGenerator.resource(dir: 'js', file:'application.js')
3log.info grailsLinkGenerator.resource(dir: 'css', file: 'app.css')