Grails: How to access action/controller/param inside a service

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.

Tagged with: , , , ,
Posted in Grails, Groovy, Java

Leave a Reply

Your email address will not be published. Required fields are marked *

*

Anti-spam protection

Prove that you are Human by typing the emphasized characters:


Protected by Gab Captcha 2

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>