grails override redirect controller method

耗尽温柔 提交于 2019-12-05 00:30:46

问题


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.


回答1:


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
}



回答2:


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))
  }
}


来源:https://stackoverflow.com/questions/5316727/grails-override-redirect-controller-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!