开发者

grails override redirect controller method

I am trying to override the default controller redirect method and cannot seem to get the following bit of code to work.

I have created a plugin and I'm trying to use the "doWithDynamicMethods" to replace the redirect.

def doWithDynamicMethods = {ctx ->
   application.controllerClasses.each() { controllerClass ->
      replaceRedirectMethod(controllerClass)
   }
}

void replaceRedirectMethod(controllerClass) {
   def oldRedirect = controllerClass.metaClass.pickMethod("redirect", [Map] as Class[])
   controllerClass.metaClass.redirect = { Map args, Map params ->
      // never seems to get here    开发者_开发技巧
   }
}

Do I have the signature wrong or am I missing something? The reason I'm doing this is I'd like to change the uri of the redirect if a certain condition is met but with logging/print statements I see that it is going in the "replaceRedirectMethod" upon application startup/compile but it doesn't go in there when doing a redirect via the controller once the app is started.


Yes, the signature is wrong - redirect takes a single Map parameter (see the declaration in org.codehaus.groovy.grails.plugins.web.ControllersGrailsPlugin.registerControllerMethods())

So it should be

controllerClass.metaClass.redirect = { Map args ->
   // pre-redirect logic
   oldRedirect.invoke delegate, args
   // post-redirect logic
}


Also note that if you want the redirect method override to be reapplied after modifying the source code of a controller, you need to do the following:

def watchedResources = [
  "file:./grails-app/controllers/**/*Controller.groovy"]

def onChange = { event ->
  if(!(event.source instanceof Class)) return

  if(application.isArtefactOfType(ControllerArtefactHandler.TYPE, event.source))
  {
    replaceRedirectMethod(application.getArtefact(ControllerArtefactHandler.TYPE,
                                                  event.source.name))
  }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜