Use case
Even though a service should be stateless and application-/context-independent, I needed to access the current controller and action from inside a service class.
Namely I have a URL-Service, which provides various kinds of dynamic URL methods. One of these methods is a createLink-clone (I got that from here).
Further I want both the controller and the action to get set dynamically in case one of those parameters is not specified.
Solution
For this I need to get the current context’s attributes.
RequestContextHolder.currentRequestAttributes().params["action"]
Finally, this is the createLink method:
def createLink( def controller, def action, def params ) { def g = new org.codehaus.groovy.grails.plugins.web.taglib.ApplicationTagLib() def link = g.createLink( controller: controller?:RequestContextHolder.currentRequestAttributes().params[ "controller" ], action: controller?:RequestContextHolder.currentRequestAttributes().params[ "action" ], params: params?:[], absolute: 'true' ) return link }
Side note
But please have in mind that in some special cases the params-map might not contain the values for controller/action/params. So you’d better provide a fallback-functionality.