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 link in grails services.

First inject the grailsLinkGenerator bean in the service

def grailsLinkGenerator

then call link method of the the bean to create link

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

output

/appName/controllerName/actionName
http://localhost:8080/appName/controllerName/actionName
http://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.

log.info grailsLinkGenerator.link(controller: 'controllerName', action: 'actionName', id: 1, base: grailsLinkGenerator.serverBaseURL)
log.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

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