3

Is there a way of executing some piece of code before any controller action gets called?

I need to set a session variable based on the value of a get parameter, without taking into account which controller gets called.

Of course, once this processing is done, the request needs to follow its normal way to the corresponding controller/action.

Thanks

4

2 回答 2

4

听起来您想使用过滤器

例如grails-app/conf/MyFilter.groovy

class MyFilter {
    def filters = {
        extractSomething(controller: '*', action: '*') {
            before = {
                session.setAttribute('foo', params['paramName'])
            }
        }
    }
}
于 2011-03-24T15:47:41.193 回答
2

如果与多个或所有控制器一起使用,过滤器很好,但可能会变得昂贵。您也可以尝试拦截器:

def beforeInterceptor = {
       session.setAttribute('foo', params['paramName'])
}

http://www.grails.org/Controllers++-+拦截器

于 2011-03-24T18:24:58.497 回答