Override Grails redirect method

前端 未结 1 1896
夕颜
夕颜 2021-01-27 23:54

I\'m carrying the locale of my Grails application in the URL, such as

http://myapp.com/LANG/controller/action/id.

Therefore, I adjusted the URLMappings.groovy wi

相关标签:
1条回答
  • 2021-01-28 00:44

    The easiest way to do this in your application would be to use a bit of meta programming and the BootStrap.groovy for your Grails application. The following is just a simple example of what that might look like:

    import org.codehaus.groovy.grails.web.servlet.GrailsApplicationAttributes
    
    class BootStrap {
    
        def init = { servletContext ->
            def ctx = servletContext.getAttribute(GrailsApplicationAttributes.APPLICATION_CONTEXT)
            def app = ctx.getBean("grailsApplication")
            app.controllerClasses.each() { controllerClass ->
                def oldRedirect = controllerClass.metaClass.pickMethod("redirect", [Map] as Class[])
                controllerClass.metaClass.redirect = { Map args ->
                   // new pre-redirect logic
                   if (!args['params']) args['params'] = [:] // just in case redirect was called without any parameters
                   args['params']['whatever'] = 'something' // add something into the parameters map
    
                   oldRedirect.invoke delegate, args
                   // new post-redirect logic
                }
            }
    
        }
        def destroy = {
        }
    }
    

    The above example just wraps the implementation for redirect on all controllers within your Grails application and injects a new parameter called whatever with the value of something.

    The above was tested (quickly) using Grails 2.4.2.

    0 讨论(0)
提交回复
热议问题